问题
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