2016-03-22 3 views
1

2つのシンプルなコンポーネントがあります。 1つはリスティングユーザー用、もう1つは詳細表示用です。ngIf条件が満たされたときに追加データを取得します

私は特定のユーザーを選択すると、このユーザーは変数selectedUserにバインドされます。詳細コンポーネントではngIfが満たされ、このユーザーに関連するデータをさらに取得するよう追加の要求を行います。

これを実装する適切な方法は何ですか?私はカスタム関数を作成すると、それは私のAPIに大量のリクエストを作り始めるが、私はそれを一度しか必要としない。ありがとう!

@Component({ 
    selector: 'users', 
    template: ` 
     <div *ngFor="#user of users" 
      (click)="onSelect(user)"> 
       {{ user.name }} 
     </div> 
     <user-detail [user]="selectedUser"></user-detail> 
    ` 
export class UserComponent { 
    onSelect(user: IUser) { 
     this.selectedUser = user; 
    } 
} 

@Component({ 
    selector: 'user-detail', 
    template: ` 
     <div *ngIf="user"> 
      {{ user.name }} {{ user.id }} 
      <div *ngFor="task of tasks"> <-- this is what i actually try to fetch 
      </div> 
     </div> 
` 

export class UserDetailComponent { 
    @Input() user: IUser[]; 
} 

答えて

1

私はあなたがそのngIfディレクティブuser-detail以上のコンポーネントの使用にお勧めしたい:

は、ここに私のコードです。それでngDoCheck & ngフックの内側にuser-detailのコンポーネントを発火させることができますuserの値がInputに変更されました。

<user-detail *ngIf="selectedUser" [user]="selectedUser"></user-detail> 

あなたはスコープ機能でNG-IFを使用することができコンポーネント

@Component({ 
    selector: 'user-detail', 
    template: ` 
     <div> 
      {{ user.name }} {{ user.id }} 
      <div *ngFor="task of tasks"> <-- this is what i actually try to fetch 
      </div> 
     </div> 
` 

export class UserDetailComponent implements DoCheck { 
    @Input() user: IUser[]; 

    ngDoCheck(){ 
     //stuff which will fireup when everytime component user gets changed. 
    } 
} 
+0

で、その後

var busy = false; scope.Validate = function() { //Do validation if(/*condition*/) { if(!busy) { busy = true; /*Do your fetch for data and set busy = false when done*/ } return true; } else return false; } 

はい、それは動作します:

(JavaScriptで)線に沿って何かを!条件が満たされると、コンポーネントが挿入されます。しかし、私が選択したユーザーを変更すると、それは再び初期化されません。おそらくここでngOnChangesを使うべきですか?どういうわけか結果をキャッシュすることはできますか?あなたはJavaScriptで私が知っているさせるためにあまりにも – v01d

+1

ので、その後 'ngDoCheck'がngOnInit' –

-3

。 trueまたはfalseを返す限り、そこで検証を実行して余分なデータを取得することもできます。要素コールng-if="Validate()"

+1

これはAngular1ものではない代わりに、'のapproapriateだろう.. –

+0

..:D – MiltoxBeyond

+0

おかげ角度行うことができますv01d @ –

関連する問題