angular ViewChild ContentChild 系列的查询参数

官方说明

官方文档
在调用 NgAfterViewInit 回调函数之前就会设置这些视图查询。
元数据属性:

  • selector - 用于查询的指令类型或名字。
  • read - 从查询到的元素中读取另一个令牌。

所支持的选择器包括:

  • 任何带有 @Component 或 @Directive 装饰器的类
  • 字符串形式的模板引用变量(比如可以使用 @ViewChild('cmp') 来查询 <my-component #cmp>
  • 组件树中任何当前组件的子组件所定义的提供商(比如 @ViewChild(SomeService) someService: SomeService )
  • 任何通过字符串令牌定义的提供商(比如 @ViewChild('someToken') someTokenVal: any )
  • TemplateRef(比如可以用 @ViewChild(TemplateRef) template; 来查询 )

代码:

<div #testBox [appElementTitle]="'属性指令测试'" [appCopyAttr]="'https://liangyuetian.cn/'">
    appElementTitle 属性指令测试 appCopyAttr 属性指令测试
</div>
<div #box [appElementTitle]="'这是box的title'" [appCopyAttr]="'https://baidu.com.cn/'">
    appElementTitle 属性指令测试 appCopyAttr 属性指令测试
</div>
export class AppComponent implements OnInit, AfterViewInit {
    @ViewChild('testBox', {read: ElementRef}) elBox: ElementRef;
    @ViewChild('testBox', {read: CopyAttrDirective}) copy: CopyAttrDirective;
    @ViewChild('testBox', {read: ElementTitleDirective}) titles: ElementTitleDirective;

    @ViewChild('box', {read: ElementRef}) elBox2: ElementRef;
    @ViewChild('box', {read: CopyAttrDirective}) copy2: CopyAttrDirective;
    @ViewChild('box', {read: ElementTitleDirective}) titles2: ElementTitleDirective;

    keyUpSearch($event: { [key: string]: any }) {
        console.log($event.code, $event.key, $event);
    }
    ngOnInit() {
    }
    ngAfterViewInit() {
        console.log('one', this.elBox, this.copy, this.titles);
        console.log('tow', this.elBox2, this.copy2, this.titles2);
    }
}

效果:
983934-20190403234450405-1593908630.png

转载于:https://www.cnblogs.com/daowangzhizhu-pt/p/10652497.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值