簡単に言えば、私はAngular 4アプリを持っています。これにはアンドロイドに触発されたフローティングアクションボタンが含まれています。このボタンをクリックすると、 (ページ内容は基本的に)。私は角度4のルータを使用していますが、違いがあれば、ビューチャイルドのアプローチではいくつかの懸案事項が発生しました。なぜなら、現在アクティブなコンポーネントがいつもわからないからです。可能ならば、単一のテンプレート。アプリコンポーネントから角度4 - 呼び出し子コンポーネントメソッド
私はこれをViewChildデコレータ、ContentChildデコレータ、イベント、サービス、これまで絶対ににしようとしましたが、は機能していました。この時点で私は本当に複雑なのか、それともPEBCAKなのかは分かりません。
問題のボタンがapp.component
内に含まれている - ここでの一般的なアイデアがある
<div class="fab-container">
<button class="btn btn-warning btn-fab" (click)="fabAction()">
+
</button>
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
currentUrl: string = null;
constructor(private router: Router, private currentRoute: ActivatedRoute) {}
ngOnInit() {
this.router.events.subscribe((val) => {
this.currentUrl = this.router.url;
});
}
}
app.component.html
(簡潔にするためだけのボタン)このボタンがあるときにクリックすると、子コンポーネントのメソッドfabAction()
が実行されます。
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.scss']
})
export class CourseListComponent implements OnInit {
courses: Course[];
showFilter: boolean = false;
constructor(
private courseService: CourseService
) { }
ngOnInit(): void {
this.getCourses();
}
getCourses(): void {
this.courseService.getCourses().then(courses => this.courses = courses);
}
// Should execute this method when button is clicked on app component
fabAction(): void {
console.log('responding to click on parent component');
this.showFilter = !this.showFilter;
}
}
</div>
価値は何も各コンポーネントは、それが工場のボタンがアプリのコンポーネント上でクリックされたときに実行する独自のアクションの必要がありますことを、いくつかは、モーダルを開き、他の人がいくつかはそれをリダイレクトする、物事を表示/非表示されますされていないことの一つコンポーネント自体にこの動作を指定できるのは本当にいいですね。
公式の角型文書を読むことで、私は答えよりも多くの質問を残してしまったので、誰かがこれに対処するより理想的な方法を提案できるように、すべてを清潔なスレートに戻しました。
編集は - 要求
<header *ngIf="currentUrl != '/landing'">
<div class="brand">
<img src="/assets/circle-logo.png" />
</div>
<nav>
<div class="page-title">
<h2>{{ page?.title }}</h2>
<h4>{{ page?.strapline }}</h4>
</div>
<ul class="header-nav">
<li [routerLink]="['/courses']">Courses</li>
<li>Dashboard</li>
<li>Community</li>
<li>Blog</li>
<li>About</li>
</ul>
<div class="fab-container">
<button class="btn btn-warning btn-fab" (click)="fabAction()">
+
</button>
</div>
</nav>
</header>
<router-outlet></router-outlet>
<app-footer></app-footer>
としてapp.component.html
の完全なマークアップはここに私は私のルートを定義私のアプリルーティングモジュールのどの成分がどの経路を表示する(4角度ヒーローのツアーで行われるようデモ)
const routes: Routes = [
{ path: '', redirectTo: 'landing', pathMatch: 'full' },
{ path: 'landing', component: LandingComponent },
{ path: 'courses', component: CourseListComponent },
{ path: 'course/:id', component: CourseComponent }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
ここでコンポーネントを作成していますか?子コンポーネントをどのように組み込むかを示すコードを投稿することができます –
コンポーネントはルーターアウトレット経由で角度ルータに表示されています。元の投稿に 'app.component.html'のマークアップを追加します – DLMousey