Serhii
Serhii

Reputation: 7563

Angular model data from parent Controller

I have an controller, in template of it I pass data to child:

    <app-lexema-item [lexema]="lexema"></app-lexema-item>

the child controller is:

@Component({
  selector: 'app-lexema-item',
  templateUrl: './lexema-item.component.html',
  styleUrls: ['./lexema-item.component.css']
})
export class LexemaItemComponent implements OnInit {
  @Input() lexema: Lexema;
  constructor() {}
  ngOnInit() {}
}

and template for it:

<div class="container">
  <div class="row">
    <div class="col-xs-10">
      <p>
        <br/> {{ lexema.name }} ({{ lexema.type }})
      </p>
    </div>
  </div>
</div>

Data passed correctly and injected into the child controller.

Question

On next step I try add input for lexema-item.component.html:

    <input type="text" ngModel name="lexema.name">

but it doesn't work. I know that issue is in using lexema.name in name field but I do not know how to handle it (I tried alternative different cases name=[(lexema.name)], name="[(lexema.name)]") but unsuccessfully.

Is there any cool elegant solution?

Upvotes: 0

Views: 46

Answers (2)

Gregor Doroschenko
Gregor Doroschenko

Reputation: 11696

You should use [(ngModel)] instead of name=[(lexema.name)]. Hint: If you get undefined erros in console, hange [(ngModel)]="lexema.name" to [(ngModel)]="lexema?.name".

Change this:

 <input type="text" ngModel name="lexema.name">

to this:

 <input type="text" [(ngModel)]="lexema.name" name="name">

By using [(ngModel)] you must use name-attribute, beacuse it's important for template driven forms. Also you should import FormsModule into your app.module.ts.

import { FormsModule } from '@angular/forms';

For more information read the official angular docs about template driven forms.

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68665

First you will get an error of undefined element, because input binding will go after the markup is initialized. So for first we need to make sure that our element will be visible if the input is assigned.

If you want to bind to the name property.

<input type="text" ngModel name="{{ lexema?.name }}">

If you want to bind to the value of the input, you need to use ngModel with two-way binding.

<input type="text" [(ngModel)]="lexema?.name">

Upvotes: 1

Related Questions