[英]Passing values from parent component to child component in angular
我正在嘗試構建一個angular
組件,它根據父元素提供的 src、寬度和高度顯示圖像。
這是我的代碼:
我的圖片標志.component.html
<img #imgDiv src="{{name}}" >
我的形象標志.component.ts
export class MyImageLogoComponent implements OnInit {
@Input() name;
@Input() width = "100px";
@Input() height = "100px";
@ViewChild("imgDiv") imgDiv: ElementRef;
constructor() { }
ngOnInit() {
this.imgDiv.nativeElement.setAttribute("width", this.width);
this.imgDiv.nativeElement.setAttribute("height", this.height);
}
}
父組件.html
<app-my-image-logo [name]="userDetails.profilePic" [width]="'50px;'" [height]="'50px;'"></app-my-image-logo>
這非常有效,但我試圖不在ngOnInit
中初始化width
和height
,而是使用ngStyle
如下:
<img [ngStyle]="{'width': width, 'height': height}" src="{{name}}" >
但這是行不通的。 我什至嘗試了以下方法,但即使這樣也行不通:
<img width="{{width}}" height="{{height}}" src="{{name}}" >
我究竟做錯了什么? 另外,這是為組件分配 css styles 的正確方法嗎?
您可以這樣做(在您的子組件中)來修改屬性:
<img [attr.width]="width" [attr.height]="height">
您可以通過以下方式與孩子共享父母的css文件:
@Component({
selector: 'lions',
templateUrl: 'lions.component.html',
styleUrls: ['lions.component.css', '../zoo.component.css']
})
(動物園是父母,獅子是孩子)
但是在您的情況下,我只是將子級的寬度和高度設置為100%,例如lion.css:
:host() { width: 100%; height: 100% }
( :host()
表示組件的根標記)
在子組件中,您必須將HTML更改為
<img [width]="width" [height]="height" [src]="name" >
當我們嘗試在 ngOnInit 中訪問時,imgDiv 可能未定義。 嘗試在 ngAfterViewInit 中執行此操作,但我不確定我們是否可以更改寬度,因為視圖已經繪制完成
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.