如何在Angular中从父组件到子组件共享数据?

时间:2019-02-01 12:27:07

标签: angular typescript parent-child angular7

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

这是我的父component.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>

这是我的父组件。

 city: string;

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

这是我的子component.html

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

这是在子component.ts

@Input() testCity: string;

3 个答案:

答案 0 :(得分:1)

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

// 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
}

答案 1 :(得分:0)

您可以创建一个保存共享数据的服务

export class cityService { 城市:字符串 }

在您的app.module中提供此服务

然后在您想要的任何地方注入此服务

在每个组件构造器中

答案 2 :(得分:0)

1。使用*ngIf有条件地在您的子组件中显示数据

如果您的问题是城市的中间值显示在子组件中,而用户在父组件中键入城市名称,而您只想在用户单击时在子组件中显示最终的城市名称getWeather会将天气传递给您的孩子部分,您可以决定仅在孩子也有天气时在孩子模板中显示城市。

那么您不必在子组件中获得testCity的中间值,因为只有在设置了天气时才显示城市。

孩子

<p *ngIf="weather">{{ testCity }}</p>
<div>{{ weather }}</div>
@Input() testCity: string;
@Input() weather: string;

父母

<input matInput type="text" [(ngModel)]="city">
<button mat-button (click)="getWeather()">Get Weather</button>

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

getWeather() { 
 this.weather = 'Sunny';
}

2。使用Subject显式将数据作为事件发送给子对象

如果您需要将某些数据作为事件从父级发送给子级,则可以在父级中创建一个Subject并将其作为Observable传递给您订阅值更改的子级

孩子

<p>{{ city$ | async }}</p>
@Input() city$: Observable<string>;

父母

如果您只需要getWeather函数和子组件中的城市,则可以删除[(ngModel)]="city"并直接从输入中读取值并将其传递给getWeather

<input #cityInput matInput type="text">
<button mat-button (click)="getWeather(cityInput.value)">Get Weather</button>

<app-city-weather [city]="currentCity.asObservable()"></app-city-weather>
currentCity: Subject<string> = new Subject<string>();

getWeather(city: string) { 
 // send current city to child
 this.currentCity.next(city);
}