如果同一组件用于添加和编辑功能,如何将 ngModel 绑定到输入元素?
How to bind ngModel to Input Element if the same component is used for Add as well as Edit feature?
场景是:有两个组件,一个用于添加状态,另一个用于查看可点击并重定向到 "Add" 组件的状态列表。
我想使用相同的 "Add" 组件进行添加和编辑;
这是我的 add.component.ts 代码:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import 'rxjs/add/operator/switchMap';
import { StateService } from './state.service';
import { State } from '../models/state';
import { Params } from '@angular/router/src/shared';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-add',
templateUrl: './add.component.html'
})
export class AddComponent implements OnInit {
state$: Observable<State>;
constructor(private route: ActivatedRoute,
private router: Router,
private stateService: StateService) { }
ngOnInit() {
this.state$ = this.route.paramMap.switchMap((params: ParamMap) => this.stateService.getState(params.get('id')));
}
}
这是我的 add.component.html;
..................
<div class="col-sm-10">
<div *ngIf="state$ | async as state">
<h3>"{{ state.name }}"</h3>
</div>
<input type="text" [(ngModel)]="state$.name" class="form-control" id="" style="max-width:500px"/>
</div>
...................
ngIf 部分显示正确的数据;但输入文本框未显示任何值。
请帮助正确的方法。
在 *ngIF
中,您使用 state
作为 state$|async
的别名。而这个别名 state
范围在 *ngIf
内。这就是为什么 state
在 ngModel
、
范围之外不起作用的原因
<div *ngIf="state$ | async as state">
<h3>"{{ state.name }}"</h3>
</div>
如果您不想在 ngModel 中使用管道过滤器,请使用此选项
<input type="text" [(ngModel)]="state$.name" class="form-control" id="" style="max-width:500px"/>
场景是:有两个组件,一个用于添加状态,另一个用于查看可点击并重定向到 "Add" 组件的状态列表。
我想使用相同的 "Add" 组件进行添加和编辑;
这是我的 add.component.ts 代码:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import 'rxjs/add/operator/switchMap';
import { StateService } from './state.service';
import { State } from '../models/state';
import { Params } from '@angular/router/src/shared';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-add',
templateUrl: './add.component.html'
})
export class AddComponent implements OnInit {
state$: Observable<State>;
constructor(private route: ActivatedRoute,
private router: Router,
private stateService: StateService) { }
ngOnInit() {
this.state$ = this.route.paramMap.switchMap((params: ParamMap) => this.stateService.getState(params.get('id')));
}
}
这是我的 add.component.html;
..................
<div class="col-sm-10">
<div *ngIf="state$ | async as state">
<h3>"{{ state.name }}"</h3>
</div>
<input type="text" [(ngModel)]="state$.name" class="form-control" id="" style="max-width:500px"/>
</div>
...................
ngIf 部分显示正确的数据;但输入文本框未显示任何值。
请帮助正确的方法。
在 *ngIF
中,您使用 state
作为 state$|async
的别名。而这个别名 state
范围在 *ngIf
内。这就是为什么 state
在 ngModel
、
<div *ngIf="state$ | async as state">
<h3>"{{ state.name }}"</h3>
</div>
如果您不想在 ngModel 中使用管道过滤器,请使用此选项
<input type="text" [(ngModel)]="state$.name" class="form-control" id="" style="max-width:500px"/>