ngModel not working in two different components?

939 views Asked by At

The title is pretty self-explanatory, so - I put an input element in app.component.html file, this is the code: <input type="text" name="titleInput" id="titleInput" [(ngModel)]="titleInput"> Then i tried making an h1 element in another component, as I wanted it to display what was typed in the input field. Didn't work. Made an h1 element in app.component - works fine. I searched a lot, but didn't find anything. Can you help me?

2

There are 2 answers

1
Mohsen Kamrani On

You can use your model titleInput which is manipulated through the input to display, in your case, in your header tag using interpolation, i.e. {{.}}.

For example:

<div>
    <h1>{{titleInput}}</h1>
    <input type="text" name="titleInput" id="titleInput" [(ngModel)]="titleInput"/>
</div>

You can see it working here.

1
Swoox On

There are two ways.

Either do it with a child parent relationship with @Input. https://angular.io/guide/component-interaction (see other post).

Or use LocalStorage.setItem('titleInput', titleInput); in first component.

And in second LocalStorage.getItem('titleInput'); and LocalStorage.removeItem('titleInput');