首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ngModel未绑定到组件参数

ngModel未绑定到组件参数
EN

Stack Overflow用户
提问于 2020-08-02 20:42:53
回答 1查看 171关注 0票数 0

目标:我正在尝试更新html模板中危机对象的"name“属性。

问题:当用户编辑输入字段时,ngModel指令不会将初始crisis.name值读入html-input元素,也不会更新名称。

问题可视化:

Empty Input field that should be bound to crisis.name

Html模板:

代码语言:javascript
复制
<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>

组件:

代码语言:javascript
复制
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 });
  }

}
EN

回答 1

Stack Overflow用户

发布于 2020-08-02 21:42:56

您必须将双向绑定拆分为两个单向绑定:

代码语言:javascript
复制
<input [ngModel]="(crise | async)?.name" (ngModelChange)="loadValueChange($event)"> 

现在,在您的组件中创建一个新的loadValueChange(NewValue)方法,该方法将更新observable上的值

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63216129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档