在模板中将 ngModel 与异步管道一起使用

Using ngModel with async pipe in template

我的模板中现在有这样的东西

<ng-container *ngIf="state | async as stateObject">
  <select [(ngModel)]="stateObject.name">
    <option>Select</option>
  </select>
<ng-container>

我的问题是如何在我的组件中获取 stateObject.name 的值,因为我的组件中没有任何订阅。

My question is how do I get the value of stateObject.name inside my component, because I dont have any subscription in my component.

你可以

<select [(ngModel)]="stateObject.name" (ngModelChange)="doSomething($event)">
    <!-- … -->
</select>

然后在你的组件中

doSomething (model: State): void {
    console.log(model); // or whatever
}

但这并不是我认为最好的主意。最好不要在这里使用 async 管道,而是在您的组件中显式管理订阅:

<ng-container *ngIf="stateObject">
    <select [(ngModel)]="stateObject">
        <!-- … -->
    </select>
</ng-container>

// ===

@Component({ … })
public YourComponent extends Component implements OnDestroy {

    public stateObject: State;
    private destroy$ = new Subject();

    constructor(private state: StateService) {
        state
            .takeUntil(this.destroy$)
            .subscribe(state => this.stateObject = state);
    }

    public ngOnDestroy(): void {
        this.destroy$.next();
        this.destroy$.complete();
    }

}

这也会让您更好地控制要做什么,例如,如果 state 在您的表单脏时发出。