在Angular中使用ViewChild选择特定的属性指令 [英] Select specific attribute directive using ViewChild in Angular

查看:207
本文介绍了在Angular中使用ViewChild选择特定的属性指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个元素利用了 mdTooltip 属性指令(这就是它的含义称为?

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>'
})

我可以使用以下方法在iconOne上调用toggle()方法:

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();
    }
}

我理解它的方式,即我应用属性指令的元素,变成了属性指令的类型.因此,我尝试选择iconTwo这样:

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不是函数

_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?

推荐答案

使用额外的参数使Angular返回对指令的引用

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

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

我认为您不需要为组件做这些事情.如果指令在元数据中使用exportAs,则可以将ref变量分配给exportAs属性.

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>

这里是一个例子:

 @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();
    }
  }

这篇关于在Angular中使用ViewChild选择特定的属性指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆