【问题标题】:how to link a condition to a button如何将条件链接到按钮
【发布时间】:2020-06-26 15:53:58
【问题描述】:

在我的 Angular 应用程序中。我正在使用子组件和父组件。我的子组件具有“只读”属性。我的父组件有一个编辑按钮。如何将父组件中的编辑按钮链接到子组件中的只读。当我单击编辑按钮时,我想禁用子组件中的只读选项。请指导我如何实现这一点。

子组件

<form[formGroup]='childForm'>
    <div>
        <inputformControlName = "childttest" [readonly] =  "isreadonly">
    </div>
</form>

父组件

<form[formGroup]='parentForm'>
<button (click)= disableReadonly()> </button>
    <childComponent [childForm]= "parentForm.controls.childForm" ></childComponent>
</form>

父组件TS

ngOnInit() {
    this.parentForm = this.FormBuilder.group({
        test1: [''],
        childForm: this.FormBuilder.group({
            childtest: ['']
        })
    });
    this.parentForm.controls.childForm.controls.childtest.setValue(this.data);
}

disableReadonly(){

}

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以尝试使用template reference variable 并在按钮的事件处理程序中切换isreadonly 的值。试试下面的

    父组件模板

    <form [formGroup]='parentForm'>
    <button (click)="child.isreadonly = !child.isreadonly">Toggle child readonly</button>
      <childComponent #child [childForm]="parentForm.controls.childForm" ></childComponent>
    </form>
    

    这里#childchildComponent标签的模板引用变量。 isreadonly 应该是 public 才能正常工作。如果您希望将其设为private,则可以将其设为Input(),并将其传递给类似于childForm 变量。

    工作示例:Stackblitz

    【讨论】:

    • 嗨,我试过了,但它不起作用。如果可能的话,你能不能给我一个工作的例子。
    • @rja:我已经更新了答案以包含一个工作示例。
    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    相关资源
    最近更新 更多