在模板中使用带有异步管道的ngModel

问题描述 投票:1回答:1

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

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

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

rxjs angular2-template
1个回答
2
投票

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

你可以做到

<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在您的表单变脏时发出,这也可以让您更好地控制该怎么做。

© www.soinside.com 2019 - 2024. All rights reserved.