【问题标题】:How can I bind multiple actions to a single Angular output?如何将多个操作绑定到单个 Angular 输出?
【发布时间】:2021-09-20 22:05:34
【问题描述】:

如何在不创建任何其他方法的情况下将多个操作绑定到单个 Angular 输出?

一个示例是根据自定义组件的输出更新formControl 的值,并将formControl 标记为脏。

【问题讨论】:

    标签: angular binding angular-template angular-template-variable


    【解决方案1】:

    您可以将 数组 绑定到 HTML 模板中的输出,这使您能够触发多个操作:

    模板:

    <ul>
        <li style="cursor:pointer" 
            *ngFor="let value of values"
            (click)="[myFormControl.setValue(value), myFormControl.markAsDirty()]">{{value}}
        </li>
    </ul>
    <ul>
        <li>Form Control Value: {{myFormControl.value}}</li>
        <li>Form Control Dirty: {{myFormControl.dirty}}</li>
    </ul>
    <button (click)="myFormControl.reset()">Reset Form Control</button>
    

    组件:

    import { Component } from '@angular/core';
    import { FormControl } from '@angular/forms';
    
    @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
        myFormControl = new FormControl(null);
        values = ['spring', 'summer', 'autumn', 'winter'];
    }
    

    Stackblitz example.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 2018-09-20
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多