angular - 从组件到组件的角度重用属性
问题描述
我从 Angular 开始,完成了教程,试图掌握概念,但我遇到了一个看似简单的问题。试图用谷歌搜索,但我无法解决这个问题。
在 Angular 5 中,您将如何在组件之间重用属性(此处为标题)?假设我title
定义了app.component.ts
我希望最终在login.compoment.html
??中重用的属性
app.module.ts
@NgModule({
imports: [
AppRoutingModule
],
declarations: [
AppComponent,
LoginComponent,
],
providers:[
// services
],
bootstrap: [AppComponent]
})
export class AppModule {}
app.component.ts
@Component({
selector : 'app-root',
template : `<router-outlet></router-outlet>`
})
export class AppComponent {
title = 'A global title...';
}
登录组件.ts
@Component({
selector : 's-login-pg',
templateUrl: './login.component.html',
styleUrls : [ './login.scss'],
})
export class LoginComponent implements OnInit {
// should title be referenced here?
// should the AppComponent be imported again, as they are already both defined in app module ?
}
login.component.html
<div>{{title}}</div> <!-- I want the title in app.component.ts to show up -->
你能建议如何处理这个问题吗?
解决方案
@Input()
您可以通过/@Output()
或通过共享的 Angular 凋零传递数据Service
。
如果您将数据从父组件传递到子组件,则建议使用@Inout / @Output (尽管您可以以相同的方式将其更深地发送)。
如果您更深入地传递数据,建议使用服务。在您的情况下,您似乎将其传递得更深。所以你要做的是创建一个新custom-service.service.ts
文件,将其添加到 providers 数组中app.module.ts
(因此它成为整个应用程序的单例),将此服务注入到所有通信的组件中。存储服务中的属性 - title: string
。
在app.component.ts
您注入此服务时:
import {CustomService} from '...path'
title = 'My title';
constructor(private custService: CustomService) {
}
ngOnInit() {
this.custService.title = this.title;
}
现在每个导入该服务的组件都可以访问它的title
属性并获得它的值:
import {CustomService} from '...path'
title: string;
constructor(private custService: CustomService) {
}
ngOnInit() {
this.title = this.custService.title;
}
推荐阅读
- ruby - 仅当方法尚不存在时如何实现它
- forms - 您如何翻译 TYPO3 CMS 8.7 LTS 中的 EXT:Form Buttons?
- highcharts - 仅绘制数据点的图表类型
- angular-material - Angular 6将数据加载到多选中
- speech-recognition - Google Cloud Speech API:如何获取超过 1 分钟的音频全文转录?
- c - 野牛目标的CMake自定义命令
- javascript - 复选框选中的属性不适用于 Pug
- linux - 为什么 do_execve() 执行可执行验证检查分两步而不是一步?
- jquery - 如何在 Bootstrap 范围滑块中选择反向范围?
- reactjs - 如何在 React ui-fabric 库中自定义 GroupedList 组件中的标题