在Angular中,可以通过自定义指令来改变元素的输入。以下是一个示例:
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[appChangeInput]'
})
export class ChangeInputDirective {
constructor(private elementRef: ElementRef) { }
@Input('appChangeInput') inputValue: string;
ngOnInit() {
this.elementRef.nativeElement.value = this.inputValue;
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
`
})
export class ExampleComponent {
inputValue: string = '默认值';
changeInput() {
this.inputValue = '新的输入值';
}
}
在上述示例中,ChangeInputDirective是一个自定义指令,它接收一个名为inputValue的输入属性。在指令的ngOnInit方法中,通过ElementRef来获取元素引用,并将其值设置为inputValue的值。
在ExampleComponent组件中,我们使用[appChangeInput]指令绑定了一个名为inputValue的属性。当点击按钮时,changeInput方法会改变inputValue的值,从而改变输入框的内容。
上一篇:Angular指令改变颜色