简体   繁体   中英

How can I bind multiple actions to a single Angular output?

How can I bind multiple actions to a single Angular output, without creating any additional methods?

An example would be updating the value of a formControl based on an output from a custom component and also marking that formControl as dirty.

You can bind an array to the an output in your HTML template, which enables you to trigger multiple actions:

Template:

<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>

Component:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM