2つのdivにクラスを追加するスクリプトを実行しようとしています。これはアコーディオン効果をもたらします。getElementByClassNameはNgForでNullを返します
私はJSONファイルを使用してデータをロードし、NgFor
を使用してdivs
をビルドしています。問題は、GetElementbyClassName()
を使用しようとするとDOMが 'Null'を返すことです。
NgForを削除して静的テキストを使用すると、このソリューションは正常に動作します。一度NgForをオンにすると、いつもNullになります。これはすべてngAfterViewInit()
の中で実行されているので、最初にdiv.accordion
を見つけることができない理由はわかりません。
HTML
<!--EVENTS-->
<section class="eventssection">
<div class="eventscontainer">
<div class="eventsbody">
<div class="eventsheader">Events</div>
<div class="notice">Our Events and programs are made possible by our members and public donations</div>
<div class="details">
<p>The Halifax Wildlife Association works hard to offer program and events to the public that help educate and generate awareness on issues that affect our wildlife and or access to.</p>
</div>
<div class="controllers">
<div id="expand" class="button">Expand All</div>
<div id="collapse" class="button">Collapse All</div>
</div>
<div class="accordioncontainer" *ngFor="let event of events">
<!--Button 1-->
<div class="accordion">{{ event.title }}</div>
<div class="panel">
<p>{{ event.description }}</p>
</div>
</div> <!--end accordion container-->
</div>
</div>
</section>
コンポーネント
非常に感謝になるので、私はプログラミングで最強のバックグラウンドを持っていない@Component({
selector: 'events',
templateUrl: "partials/events.html"
})
export class EventsComponent {
events = [];
constructor(private _eventsService: EventsService){}
ngOnInit(){
this._eventsService.getEvents()
.subscribe(resEventsData => this.events = resEventsData);
}
ngAfterViewInit() {
//Declare Variables
var accordion = document.getElementsByClassName('accordion');
var i = 0;
console.log(accordion); // tests getElementById
for (i = 0; i < accordion.length; i++) {
accordion[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
} // click
} //for loop
} // ngAfterView Init
} // export class