在Angular中,可以使用@ViewChild
装饰器来获取另一个元素的输入字段的值。以下是一个示例:
在HTML模板中,我们有两个输入字段和一个按钮:
在组件类中,我们使用@ViewChild
装饰器来获取输入字段的引用,并在getValue
函数中获取另一个输入字段的值:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-demo',
template: `
`,
})
export class DemoComponent {
@ViewChild('input1') input1: ElementRef;
@ViewChild('input2') input2: ElementRef;
getValue() {
const value = this.input2.nativeElement.value;
console.log(value);
}
}
在上述示例中,我们使用@ViewChild
装饰器来获取input1
和input2
元素的引用。然后,在getValue
函数中,我们使用this.input2.nativeElement.value
来获取input2
元素的值,并将其打印到控制台上。
请注意,@ViewChild
装饰器将返回一个ElementRef
对象,我们可以使用其nativeElement
属性来访问原生的DOM元素。