angular - 如何在 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;
解决方案
我将创建一个单独的类属性来仅为子组件存储城市值:
// 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
}
推荐阅读
- mysql - 为什么 "WHERE text != "something" 还排除所有具有 NULL 值的行?
- sql - 如何找到同一张表的父行
- python - 随机 Tkinter 窗口放置不起作用
- python - 如何从 Python 中的类的静态方法输出?
- postgresql - postgresql:在 pl pgsql 中使用时间戳变量
- objective-c - 从 Objective-C 到 Swift 的代码转换中的无效重新声明
- python - 如果我们将子类中的超类构造函数作为第一行调用,这有关系吗?
- javascript - 我们如何从 JavaScript 访问 div?
- flutter - 如何让 Flutter 应用全屏显示?
- python - python - 如何在退出python中的tkinter窗口时使代码完全停止执行?