我一直在寻找 Angular 的文档和源代码,但到目前为止没有运气。
import {
ContentChildren,
QueryList
} from '@angular/core';
import { AwesomeComponent } from './awesome.component';
@Component({
selector: 'cool-dad',
templateUrl: './cool-dad.template.html'
})
export class CoolDadComponent {
@Input() loop = false;
@Input() automatic = false;
@ContentChildren(AwesomeComponent) items: QueryList<AwesomeComponent>;
someFunc() {
this.items.forEach(item => { console.log(item)});
}
}
Run Code Online (Sandbox Code Playgroud)
通过上面的代码,我获得了对组件的引用,我可以设置它的属性并调用它的公共方法。太好了,但我还需要访问它的 html 属性,例如宽度、高度等。
import {
ContentChildren,
ElementRef,
QueryList
} from '@angular/core';
import { AwesomeComponent } from './awesome.component';
@Component({
selector: 'cool-dad',
templateUrl: './cool-dad.template.html'
})
export class CoolDadComponent {
@Input() loop = false;
@Input() automatic = false;
@ContentChildren(AwesomeComponent, { read: ElementRef }) items: QueryList<AwesomeComponent>;
someFunc() {
this.items.forEach(item => { console.log(item)});
}
}
Run Code Online (Sandbox Code Playgroud)
通过上面的代码,我获得了本机元素,因此我可以访问所有 html 属性,但我失去了对组件方法的所有访问权限。
我怎样才能得到两者?
只需在构造函数中声明以下内容 AwesomeComponent:
constructor(public elem: ElementRef) {}
Run Code Online (Sandbox Code Playgroud)
这样你就可以访问公共属性 elem 并访问每个组件的 html 属性:
someFunc() {
this.items.forEach(item => {console.log(item.elem.nativeElement.style.someHTMLProperty)});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6424 次 |
| 最近记录: |