角度 再帰的コンポーネント


同じタイプのネストされたデータを無制限に含むツリーを表示する必要がある場合があり、各レベルでコードを複製しないことをお勧めします。

この短い記事では、いくつかのレベルのネストを持つコメントの配列を入力パラメーターとして使用し、それらを再帰的に表示するコンポーネントを作成します。

データ構造


const comments:Comment[] = [ { text: "1", comments: [ { text: "1.1", comments: [ { text: "1.1.1 " } ] }, { text: "1.2", comments: [ { text: "1.2.1" } ] } ] }, { text: "2", comments: [ { text: "2.1", comments: [ { text: "2.1.1" } ] } ] } ]; 

これは、サーバーから受信する予定のデータです。 現在の例では、静的にします。

コメントコンポーネント


 @Component({ selector: 'comments', template: ` <div *ngFor="let comment of comments"> <ul> <li> {{comment.text}} <comments [comments]="comment.comments" *ngIf="comment.comments"></comments> </li> </ul> </div> `, }) export class CommentComponent { @Input() comments; } 

ご覧のとおり、コンポーネントを再帰的に呼び出します。 ネストされたコメントがない場合、コンポーネントを表示しないためにngifディレクティブが使用されます。

アプリコンポーネント


 @Component({ selector: 'my-app', template: ` <comments [comments]="postComments"></comments> `, }) export class App { postComments = postComments; } 

結果



参照資料


stackblitzの例
角る電報

Source: https://habr.com/ru/post/J351750/


All Articles