目标:我正在尝试更新html模板中危机对象的"name“属性。
问题:当用户编辑输入字段时,ngModel指令不会将初始crisis.name值读入html-input元素,也不会更新名称。
问题可视化:
Empty Input field that should be bound to crisis.name
Html模板:
<h2>Crisis</h2>
<div *ngIf="crisis$ | async as crisis">
<h3>"{{ crisis.name }}"</h3>
<div>
<label>Id: </label>{{ crisis.id }}</div>
<div>
<label>Name: </label>
<input [(ngModel)]="crisis.name" >
</div>
<p>
<button (click)="goToCrises(hero)">Back</button>
</p>
</div>组件:
export class CrisisDetailComponent implements OnInit {
// The input decorator simply allows parent components to pass down a value to it
// The parameter itself still acts as a normal attribute of the component
public crisis$: Observable<Crisis>;
constructor(
private router: Router,
private route: ActivatedRoute,
private crisisService: CrisisService
) { }
public ngOnInit(): void {
console.log('detail initialized');
this.crisis$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) => this.crisisService.getCrisis(params.get('id')))
);
}
public goToCrises(crisis: Crisis): void {
const crisisId = crisis ? crisis.id : null;
this.router.navigate(['../', { id: crisisId, foo: 'foo' }], { relativeTo: this.route });
}
}发布于 2020-08-02 21:42:56
您必须将双向绑定拆分为两个单向绑定:
<input [ngModel]="(crise | async)?.name" (ngModelChange)="loadValueChange($event)"> 现在,在您的组件中创建一个新的loadValueChange(NewValue)方法,该方法将更新observable上的值
https://stackoverflow.com/questions/63216129
复制相似问题