要将参数从视图传递给组件,并在组件中使用@ViewChild,可以按照以下步骤进行操作:
param
属性:import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() param: string;
}
import { Component, Input, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() param: string;
@ViewChild('paramElement') paramElement: ElementRef;
ngAfterViewInit() {
// 在视图初始化之后,可以通过this.paramElement来访问传递的参数
console.log(this.paramElement.nativeElement.value);
}
}
在这个示例中,我们将参数传递给子组件,并使用@ViewChild获取对输入元素的引用。然后,在视图初始化之后,我们可以通过this.paramElement来访问传递的参数。
请注意,@ViewChild装饰器使用了一个字符串参数,该参数指定了在模板中引用的本地变量的名称(在本例中为“paramElement”)。确保在模板中使用了相同的名称。