首页 > 解决方案 > 如何在 Angular 中将我的数据从父组件共享到子组件?

问题描述

我想使用 Angular(打字稿)与 2 个组件(父级和子级)共享一个字符串变量。我使用这种方法但我不喜欢它,因为当我更新输入变量时,子组件会自动更新;我只想在父组件将数据发送到子组件时更新子组件。我该怎么做?

这是我的父组件.html

 <div>
   <mat-form-field>
     <input matInput type="text" [(ngModel)]="city">
   </mat-form-field>
   <button mat-button (click)="getWeather()">
      <mat-icon matSuffix>search</mat-icon>
   </button>
 </div>

<app-city-weather [testCity]="city"></app-city-weather>

这是我的父组件.ts

 city: string;

 getWeather() { 
// I make an http request, but doesn't matter
}

这是我的孩子 component.html

<p> 
Child compoent it works!
</p>

这是子组件.ts

@Input() testCity: string;

标签: angulartypescriptparent-childangular7

解决方案


我将创建一个单独的类属性来仅为子组件存储城市值:

// Template.

 <div>
   <mat-form-field>
     <input matInput type="text" [(ngModel)]="city">
   </mat-form-field>
   <button mat-button (click)="getWeather()">
      <mat-icon matSuffix>search</mat-icon>
   </button>
 </div>

<app-city-weather [testCity]="cityChild"></app-city-weather>

// Controller.

city: string;
cityChild: string;


getWeather() { 
 this.cityChild = this.city;
 // http request
}

推荐阅读