angular - 在 ngAfterInit 中设置 nativeElement.style.color 在 Angular 中不起作用
问题描述
我正在学习 Angular,只是遇到了一个奇怪的问题。当我将 nativeElement.style.color 设置为红色时,只有当我删除上面的 img 标签时,绘图文本才会变为红色。
好像是加载问题?但我使用 ngAfterViewInit() 将 Plot 着色为红色..
希望有人可以帮助我:)
import { Component, OnInit, Input, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MovieService } from '../movie-service';
import { IMovie } from '../movie';
@Component({
selector: 'app-movie-detail',
templateUrl: './movie-detail.component.html',
styleUrls: ['./movie-detail.component.scss']
})
export class MovieDetailComponent implements OnInit, AfterViewInit {
@Input() movie: IMovie;
@ViewChild('plot', {static:false}) plotRef: ElementRef;
ngAfterViewInit(){
this.plotRef.nativeElement.style.color = "red";
}
constructor(
private route: ActivatedRoute,
private movieService: MovieService,
) { }
ngOnInit() {
this.getMovie();
}
getMovie(): void {
const id = this.route.snapshot.paramMap.get('id');
console.log("id1: ",id.toString);
this.movieService.getMovie(id)
.subscribe(movie => {
this.movie = movie;
this.readmore(movie.Plot);
console.log("movieDetail = ", movie);
console.log("id1: ",id);
});
}
}
<img src={{movie.Poster}}>
<div *ngIf=movie>
<img src={{movie.Poster}}>
<h2 class="title">{{movie.Title}} </h2>
<h5>Type: {{movie.Type}}</h5>
<h5>Year: {{movie.Year}}</h5>
<h5>Rated: {{movie.Rated}}</h5>
<h5>Genre: {{movie.Genre}}</h5>
<h5>Director: {{movie.Director}}</h5>
<h5>Actors: {{movie.Actors}}</h5>
<div>
<h5 #plot>Plot: {{movie.Plot}}
<p class="dots">...</p>
</h5>
<button id="btn-MoreLess"></button>
</div>
</div>
解决方案
因为您是在 AfterViewInit 生命周期中执行此操作,所以请使用 ngOnInit Hook 进行尝试。以下是组件https://angular.io/guide/lifecycle-hooks的可用生命周期挂钩。
样式应该用 CSS 来完成。