Search code examples
angularangular-ngmodelangular-components

How to bind ngModel to Input Element if the same component is used for Add as well as Edit feature?


The scenario is: There are two components, one is for Adding state and other is see the list of states which are clickable and redirected to "Add" component.

I want to use same "Add" component for Add and Edit;

Here is my add.component.ts codoe:

    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')));    
      }    
}

This is my 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>
  ...................

The ngIf part is showing correct data; but the input textbox is not showing any value.

Please help with correct approach.


Solution

  • Inside the *ngIF you ar using state as a alias of state$|async. And this alias state scope is inside the *ngIf. Thats why state is not working in the outside of scope in ngModel,

     <div *ngIf="state$ | async as state">
          <h3>"{{ state.name }}"</h3>
      </div>
    

    Use this if you don't want pipe filter inside ngModel

    <input type="text" [(ngModel)]="state$.name"  class="form-control" id="" style="max-width:500px"/>