How to Update a DOM without refreshing full page on Component property changes

时间:2019-04-08 12:54:59

标签: angular angular-components angular-event-emitter

My Page structure is:

<app-header></app-header>
<personal-information></personal-information>
<address></address>  // multiple address for loop
<app-footer></app-footer>

I have single JSON having personal information and multiple addresses with common field 'name' in it.

How can I update/refresh the all address component, on changing one component 'name'field, without refreshing the whole page?

1 个答案:

答案 0 :(得分:0)

You can achieve it using two-way data binding in angular. As the values change of two-way property, it will update the value of the respective template of the component in the DOM.

demo.component.html
       <app-header [name]="model.name"></app-header>
       <personal-information ></personal-information>
       <address [name]="model.name"></address>  // multiple address for loop
       <app-footer [name]="model.name"></app-footer>

demo.component.ts

       demoFn(){
           model.name="Joe"
       }

The name value 'Joe' will be passed to all the component, you have to accept the attribute name in all the component using @Input().

personal-information.component.ts

          @Input() name:string;

personal-information.component.html

        <input [(ngModel)]="name" />

Now, as will change the value in the personal-information component, it will pass it into all the component, and it will be updated in DOM if it is being used.