Search code examples
angularangular-formsangular-ngmodel

Unable to initialize default values when using ngDefaultControl in Angular


I use a child component, the child component contains the ngDefaultControl property.

el-input.component.ts:

@Component({
  selector: 'el-input',
  template: ` <input type="text" /> `,
})
export class ElInput {}

I use it like this:

@Component({
  selector: 'app-home',
  template: `
    <el-input ngDefaultControl [(ngModel)]="name"></el-input>
    <p>{{ name }}</p>
    <button (click)="onClick()">Change Name</button>
  `,
})
export class HomeComponent {
  name: string = 'Tom';

  onClick() {
    this.name = 'Jack';
  }
}

I set the initial value of name to Tom, but el-input doesn't show it. And I click the button and nothing happens enter image description here

after clicked the button:

enter image description here

how should i fix it


Solution

  • It's because [(ngModel)] is an angular directive for native html element

    If you want to create a custom input, you need to create an @Input variable inside your el element inside the elElement component and bind it inside your app

    @Component({
    selector: 'el-input',
    template: ` <input type="text" [(ngModel)]='name' /> `,
    })
    export class ElInput {
       @Input()
       name: string
    }
    
    @Component({
      selector: 'app-home',
      template: `
        <el-input ngDefaultControl [name]="name"></el-input>
        <p>{{ name }}</p>
        <button (click)="onClick()">Change Name</button>
      `,
    })
    export class HomeComponent {
      name: string = 'Tom';
    
      onClick() {
        this.name = 'Jack';
      }
    }
    

    and if you want to change the value of the variable name inside your app-home when the el input is updated, you need to create an @Output variable which will emit the new value for your app-home component

    I made a stackblitz which solve your problem here

    https://stackblitz.com/edit/angular-utyrxo