在ngAfterIniit中设置nativeElement.style.color在Angular中不起作用



我正在学习 Angular,只是遇到了一个奇怪的问题。 当我将 nativeElement.style.color 设置为红色时,绘图文本只有在删除上面的 img 标签时才会变为红色。

似乎是加载问题?但是我用ngAfterViewInit((将绘图涂成红色。

希望有人能帮助我:)

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 Lifcycle 中做的,所以试试使用 ngOnInit Hook。 以下是组件 https://angular.io/guide/lifecycle-hooks 的可用生命周期挂钩。

样式应该使用 CSS 完成。

最新更新