편집 : 아래에서이 문제를 해결했습니다. 데이터 바인딩을위한 부모 컴포넌트의 서비스에 의존하는 템플릿을 재사용하는 방법을 찾고 있다면, 계속 읽으십시오. 아니면 답장의 TL 부분으로 바로 이동하십시오.여러 구성 요소에서 데이터 바인딩이있는 템플릿 사용
나는 세 개의 별도 구성 요소로 템플릿으로 사용하는 마크 업 블록을 가지고 있습니다. 이 태그에서 템플릿을 만들어서 선택기를 요소 태그로 사용하여 이러한 구성 요소에 드롭 할 수 있습니다.
다음은이 마크 업 블록을 사용하는 세 가지 구성 요소 중 하나입니다.
featured-thread.component.html
은 이하와 같다.
세 가지 구성 요소의 각
<div *ngFor="let thread of threads" class="thread-tile">
<div class="description col-sm-12">
<div class="author-card col-sm-2">
<div>
<img src="{{thread.profileImage}}" class="img-fluid">
</div>
<div class="awards">
<span class="author-card-renown">
{{thread.renown}}
</span>
<ul class="list-inline">
<li style="padding: 2px" *ngIf="thread.numBlue > 0"><img src="./assets/blue.png"> {{thread.numBlue}}</li>
<li style="padding: 2px" *ngIf="thread.numGold > 0"><img src="./assets/gold.png"> {{thread.numGold}}</li>
<li style="padding: 2px" *ngIf="thread.numSilver > 0"><img src="./assets/silver.png"> {{thread.numSilver}}</li>
</ul>
</div>
</div>
<div class="title col-sm-10">{{thread.title}}</div>
<div class="author-date col-sm-10">
by <a href="#">{{thread.author}}</a> on {{ (thread.date | amFromUnix) | amDateFormat:'MM/DD/YY'}} at {{ (thread.date | amFromUnix) | amDateFormat:'hh:mmA'}}
</div>
<div class="participants col-sm-10">
Participants:
<ul *ngFor="let participant of thread.participants" class="participant list-inline">
<li><a href="#">{{participant}}</a></li>
</ul>
</div>
<div class="tags-container col-sm-10">
<div *ngFor="let tag of thread.tags">
<div class="tag">{{tag}}</div>
</div>
</div>
<div class="thread-metrics">
{{thread.numPosts}} posts {{thread.numFlags}} flags {{thread.numParticipants}} participants {{thread.numContributors}} contributors
</div>
</div>
은 템플릿과 같은 마크 업을 사용합니다. 유일한 차이점은 각각의 서비스가 다른 데이터를 반환한다는 것입니다.
각 구성 요소의 템플릿에 마크 업을 드롭하는 구성 요소를 만들었으므로 마크 업을 편집해야하는 경우 한 번만 편집합니다. @Input
데코레이터를 사용하여 부모에서 자식으로 데이터를 전달하고 구성 요소의 서비스를 가져 왔습니다.
import { Component, Input } from '@angular/core';
import { Thread } from './thread';
@Component({
moduleId: module.id,
selector: 'thread',
templateUrl: 'thread.component.html',
styleUrls: ['thread.component.css']
})
export class ThreadComponent {
@Input() threads: Thread[];
}
그런 다음 템플릿을 구성 요소에 드롭하고 하위 반복 인스턴스를 부모의 속성에 바인딩합니다.
<thread *ngFor="let thread of threads" [threads]="threads"></thread>
편집 : 여기에 내가 어떻게 든 아이 템플릿 내에서 데이터 바인딩을 통해 반복 반복을 생각했다. 이 선이 문제라는 것이 밝혀졌습니다. 자세한 내용은 내 대답을 참조하십시오.
featured-threads.component
만 원하는대로 동작합니다. featured-threads.service
의 로직에서 가져온 데이터를 사용하여 올바르게 표시됩니다. 다른 두 구성 요소는 부모 서비스의 논리를 우회하여 모든 스레드를 나열합니다.
왜 이런 일이 발생합니까? 또한 세 개의 개별 구성 요소 템플릿에서 동일한 마크 업을 반복하지 않아도 동일한 결과를 얻는 방법에 대해서도 개방적입니다.