简体   繁体   中英

Angular 2 - Calling function from DOM element's directive

I have some dynamically created elements with a directive. I have to call a function from element's directive in some cases. If I were created this elements statically, I would use @ViewChild('myElement') myElement in the component and something like:

<div #myelement myDirective>...</div>

in the HTML. However I couldn't to that because I creating this elements dynamically (I don't know such a method to give #myelement1 , #myelement2 , ... tags dynamically). My idea was getting the elements with document.getElementById() but I couldn't access the directive from native DOM element.

Any idea how to access the directives of these elements without using @VievChild() ?

you can do something like this :

html:

<div mask="mask1"></div>
<div mask="mask2"></div> 

ts:

import { Directive, Input} from '@angular/core';

@Directive({
  selector: '[mask]' 
})
export class Mask {
  @Input() mask: string;

  ngOnInit(){
    console.log(this.mask);
  }

  getMask(){
    return this.mask;
  }
}

import { Component, ViewChildren,QueryList } from '@angular/core';
//...
export class AppComponent {
  public user;

  @ViewChildren(Mask) masks: QueryList<Mask>;
  constructor( ){}

 ngAfterViewInit(){

    this.masks.forEach((mask)=>{
       console.log(mask.getMask());
    })
   // not sure of this
   this.masks.changes.subscribe((mask)=>{
       console.log(mask.getMask());
    })
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM