我在使用app.component.html文件访问某些子组件的属性时遇到了一些麻烦。我看过其他例子,但没有得到任何帮助。我正在使用最新的2.0.0版本。以下是我的一些代码:
app.component.ts
import { Component } from '@angular/core';
import { SellingComponent } from './selling.component';
import { GrowingComponent } from './growing.component';
@Component({
selector: 'my-app',
templateUrl: 'Areas/Plan/app/app.component.html',
styleUrls: ['Areas/Plan/app/app.component.css']
})
export class AppComponent {
}
app.component.html:
<div class="sub-nav-dropdown">
<div class="dropdown-toggle sub-nav-dropdown-button" type="button" data-toggle="dropdown">
{{subnav}}
<i class="fa fa-sort-desc"></i>
</div>
<ul class="dropdown-menu sub-nav-options" id="growSellNav">
<li>
<a routerLink="/Plan/Production/Selling" routerLinkActive="active" id="selling" class="">Selling</a>
</li>
<li>
<a routerLink="/Plan/Production/Growing" routerLinkActive="active" id="growing" class="">Growing</a>
</li>
</ul>
</div>
<router-outlet></router-outlet>
路由器插座将从grow.component.html和selling.component.html吐出html,具体取决于您选择的下拉列表中的哪个选项。在grow.component.ts和selling.component.ts中,我有一个subnav
属性,我希望在app.component.html文件中显示{{subnav}}
,但我无法将其显示在工作。以下是其他组件的代码:
export class GrowingComponent implements OnInit {
public subnav = 'Growing';
ngOnInit(): void {
console.log('initializing GrowingComponent');
}
}
export class SellingComponent implements OnInit {
public subnav = 'selling';
ngOnInit(): void {
console.log('initializing SellingComponent');
}
}
答案 0 :(得分:0)
为在组件之间发送数据提供新服务。
component.interaction.service.ts
getSubNav = new Subject();
getSubNav$ = this.getSubNav.asObservable();
sendSubnav(text:string){
this.getSubNav.next(text);
}
app.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { SellingComponent } from './selling.component';
import { GrowingComponent } from './growing.component';
@Component({
selector: 'my-app',
templateUrl: 'Areas/Plan/app/app.component.html',
styleUrls: ['Areas/Plan/app/app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
subnav:string ="";
subscription:Subscription;
constructor(private ciService:ComponentService){}
ngOnInit(){}
this.subscription = this.ciService.getSubnav$
.subscribe((res:string) => this.subnav = res);
}
ngOnDestroy(){
if(this.subscription){
this.subscription.unsubscribe();
}
}
然后,
export class GrowingComponent implements OnInit {
public subnav = 'Growing';
constructor(private ciService: ComponentService){}
ngOnInit(): void {
console.log('initializing GrowingComponent');
this.ciService.sendSubnav(this.subnav);
}
}
export class SellingComponent implements OnInit {
public subnav = 'selling';
constructor(private ciService: ComponentService){}
ngOnInit(): void {
console.log('initializing SellingComponent');
this.ciService.sendSubnav(this.subnav);
}
}