Select specific attribute directive using ViewChild in Angular

 ̄綄美尐妖づ 提交于 2019-12-11 06:15:40

问题


I have a couple elements that utilize the mdTooltip attribute directive (That's what it's called right?)

@Component({
    selector: 'status-bar',
    template: '<md-icon #iconOne mdTooltip="Connected">check_circle</md-icon>
               <md-icon #iconTwo mdTooltip="Disconnected">warning<md-icon>'
})

I'm able to call the toggle() method on iconOne by using:

export class StatusBarComponent implements OnInit {
    @ViewChild(MdTooltip) myIcon: MdTooltip;

    ngOnInit(): void {
        this.myIcon.toggle();
    }
}

The way I understand it, the element to which I apply the Attribute Directive, kind of becomes the type of the attribute directive. So I tried to select iconTwo like this:

@ViewChild('iconTwo') myIcon: MdTooltip;

This results in an error once the code is hit:

_this.myIcon.toggle is not a function

I'm guessing the item wasn't properly selected. How do I target that second icon and toggle it?


回答1:


Use an extra parameter to make Angular return you a ref to the directive

     @ViewChild('id2', { read: MyDir }) id2 : MyDir; 

I don't think you need to do it for components. If a directive uses exportAs in the metadata, you can assign ref variable to the exportAs attribute.

 <div my-dir #id2="myDir"></div>

Here is an example:

 @Directive({
    selector: '[my-dir]'
  })
  export class MyDir{
    @Input() id: number;

    toggle() {
      console.log('say hi', this.id);
    }   
  }

  @Component({
    selector: 'my-app',
    template: `
      <div>
        <button (click)="toggle2()">toggle 2</button>
        <h2 my-dir [id]="'1'">Hello 1</h2>
        <h2 my-dir #id2 [id]="'2'">Hello 2</h2>
      </div>
    `,
  })
  export class App {
    @ViewChild('id2', {read:MyDir}) id2 : MyDir;

    constructor() {
    }

    toggle2() {
      this.id2.toggle();
    }
  }



回答2:


You can also bind to it and use 1 icon.

<md-icon [mdTooltip]="connectStr">{{icon}}</md-icon>

Here's a Plunker



来源:https://stackoverflow.com/questions/43793955/select-specific-attribute-directive-using-viewchild-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!