gpt4 book ai didi

angular - 如何选择组件模板中的元素?

转载 作者:太空狗 更新时间:2023-10-29 16:44:00 27 4
gpt4 key购买 nike

有人知道如何获取组件模板中定义的元素吗? Polymer 使用 $$$ 使其变得非常简单。

我只是想知道如何在 Angular 中实现它。

以教程中的例子为例:

import {Component} from '@angular/core';

@Component({
selector:'display',
template:`
<input #myname (input)="updateName(myname.value)"/>
<p>My name : {{myName}}</p>
`
})
export class DisplayComponent {
myName: string = "Aman";
updateName(input: String) {
this.myName = input;
}
}

如何从类定义中捕获或获取 pinput 元素的引用?

最佳答案

而不是注入(inject) ElementRef并使用 querySelector或从那里类似,可以使用声明方式代替直接访问 View 中的元素:

<input #myname>
@ViewChild('myname') input; 

元素

ngAfterViewInit() {
console.log(this.input.nativeElement.value);
}

StackBlitz example

  • @ViewChild()支持指令或组件类型作为参数,或模板变量的名称(字符串)。
  • @ViewChildren()还支持以逗号分隔的名称列表(目前不允许使用空格 @ViewChildren('var1,var2,var3') )。
  • @ContentChild()@ContentChildren()做同样的事情,但在轻型 DOM(<ng-content> 投影元素)中。

后代

@ContentChildren()是唯一一个允许查询后代的

@ContentChildren(SomeTypeOrVarName, {descendants: true}) someField; 

<罢工> {descendants: true}应该是默认值,但不是 2.0.0 final,它是 considered a bug
这已在 2.0.1 中修复

阅读

如果有组件和指令 read参数允许指定应返回哪个实例。

例如ViewContainerRef这是动态创建的组件所需要的,而不是默认的 ElementRef

@ViewChild('myname', { read: ViewContainerRef }) target;

订阅更改

即使仅在 ngAfterViewInit() 时才设置 View 子级被调用并且仅在 ngAfterContentInit() 时设置内容子项被调用,如果要订阅查询结果的变化,应该在ngOnInit()中完成

https://github.com/angular/angular/issues/9689#issuecomment-229247134

@ViewChildren(SomeType) viewChildren;
@ContentChildren(SomeType) contentChildren;

ngOnInit() {
this.viewChildren.changes.subscribe(changes => console.log(changes));
this.contentChildren.changes.subscribe(changes => console.log(changes));
}

直接 DOM 访问

只能查询 DOM 元素,不能查询组件或指令实例:

export class MyComponent {
constructor(private elRef:ElementRef) {}
ngAfterViewInit() {
var div = this.elRef.nativeElement.querySelector('div');
console.log(div);
}

// for transcluded content
ngAfterContentInit() {
var div = this.elRef.nativeElement.querySelector('div');
console.log(div);
}
}

获取任意投影内容

参见 Access transcluded content

关于angular - 如何选择组件模板中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32693061/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com