【问题标题】:Angular Input Value can not be updated角度输入值无法更新
【发布时间】:2021-03-28 03:05:18
【问题描述】:

我有一个问题,我的 Angular 应用程序中的 @input 值无法更新

我的代码 在子组件中

@Input() canAddMore?: boolean;

public setButtonVisible(){

this.canAddMore = false;
}

子组件html

<button mat-mini-fab color="primary"
      (click)="setButtonVisible()" *ngIf="canAddMore">
      <mat-icon>add</mat-icon>
    </button>

如果在表单中添加了输入字段,将调用此函数

在父组件中

<app-field
                  
                  [canAddMore]="canAddMore"
                >
                </app-field>

在父组件中也有一个按钮

public canAddMore: boolean;

public setButtonVisible(){

this.canAddMore = true;
}

父组件中有一个按钮,改变canAddMore = true。

问题是,如果我在子组件中调用setButtonVisible,然后在父组件中调用setButtonVisible,

canAddMore 不会更新。

有什么解决办法吗?

【问题讨论】:

标签: angular


【解决方案1】:

@Input 是不可变的 - 您无法更改它们。您可以这样做,而不是更改它们:

class TheComponent implements OnInit {

   @Input() immutableCanAddMore?: boolean;

   private mutableCanAddMore: boolean;

   ngOnInit() {
      this.mutableCanAddMore = immutableCanAddMore;
   }

   public setButtonVisible() {
     this.mutableCanAddMore = false;
   }

}

【讨论】:

    【解决方案2】:

    您还需要进行以下更改以更新父母中的标志。

    在你的父组件 HTML 中:

    <app-field [(canAddMore)]="canAddMore"> </app-field>
    

    在您的子组件 TS 中:

    @Input() canAddMore: boolean;
    @Output() canAddMoreChange = new EventEmitter<boolean>();
    
    public setButtonVisible(){
       this.canAddMore = false;
       this.canAddMoreChange.emit(this.canAddMore);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      相关资源
      最近更新 更多