[英]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.