質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%

Q&A

解決済

1回答

8929閲覧

angular4.0のrouter-outletを使用した際の親子間の値の受け渡し

kuniatsu

総合スコア141

0グッド

0クリップ

投稿2017/05/03 12:55

編集2017/05/05 05:46

動作:https://toparent.herokuapp.com/
ソース:https://github.com/kuniatsu/routerQuestion

親コンポーネントでrouter-outletを使用して表示する際の子コンポーネントとの値の受け渡し方法がわかりません。

<router-outlet (onVoted)="onVoted($event)"></router-outlet><!--不可--> <app-child1 (onVoted)="onVoted($event)"></app-child1><!--可-->

selectorを使用した場合は、@Outputで親コンポーネントのメソッドを渡すことによって親との値のやり取りができますが、他のコンポーネントも共通するrouter-outletの場合どのようにしたら良いでしょうか?

下記では、Routerで表示している子コンポーネントのボタンは動かず、selectorで表示しているボタンは動作し、タイトルに1を加えます。
親.ts

@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app works!'; onVoted(num: number) { this.title = this.title + num; } }

親.html

<h1> {{title}} </h1> <a href=""></a> <a href="c1">child1</a> <a href="c2">child2</a> <a href="c3">child3</a> <router-outlet></router-outlet> <hr /> <app-child1 (onVoted)="onVoted($event)"></app-child1>

子.ts

@Component({ selector: 'app-child1', templateUrl: './child1.component.html', styleUrls: ['./child1.component.css'] }) export class Child1Component implements OnInit { constructor() { } ngOnInit() {} @Output() onVoted = new EventEmitter<number>(); changeTitle(){ this.onVoted.emit(1); } }

子.html

<p> child1 works! </p> <button (click)="changeTitle()">TitleSend</button>

子2.html

<p> child2 works! </p>

モジュール.ts

@NgModule({ declarations: [ AppComponent, Child1Component, Child2Component, Child3Component ], imports: [ BrowserModule, FormsModule, HttpModule, RouterModule.forRoot([ { path:'', component:Child1Component },{ path:'c1', component:Child1Component },{ path:'c2', component:Child2Component, },{ path:'c3', component:Child3Component, } ]) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

http://stackoverflow.com/questions/37662456/angular-2-output-from-router-outlet

<router-outlet>から親クラスに値のやり取りをするのはやはり無理なようなので、serviceクラスを作り、子→サービスクラス→親という流れで値を渡す方法を模索することにしました。上記urlはそのサンプルです。

投稿2017/05/07 13:54

編集2017/05/07 13:59
kuniatsu

総合スコア141

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問