将值从父组件传递到子组件中的角度

时间:2018-11-09 12:34:51

标签: angular

我正在尝试构建一个angular组件,该组件根据父元素提供的src,宽度和高度显示图像。

这是我的代码:

my-image-logo.component.html

<img #imgDiv src="{{name}}" >

my-image-logo.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);
    }
}

parent-component.html

<app-my-image-logo [name]="userDetails.profilePic" [width]="'50px;'" [height]="'50px;'"></app-my-image-logo>

这很好用,但是我尝试不初始化width中的heightngOnInit,而是按如下方式使用ngStyle

<img [ngStyle]="{'width': width, 'height': height}" src="{{name}}" >

但这不起作用。我什至尝试了以下方法,但即使这样也不起作用:

 <img width="{{width}}" height="{{height}}" src="{{name}}" >

我在做什么错?另外,这是为组件分配CSS样式的正确方法吗?

3 个答案:

答案 0 :(得分:1)

您可以通过执行以下操作来修改属性(在您的子组件中):

<img [attr.width]="width" [attr.height]="height">

答案 1 :(得分:0)

您可以通过以下方式与孩子共享父母的css文件:

@Component({
    selector: 'lions',
    templateUrl: 'lions.component.html',
    styleUrls: ['lions.component.css', '../zoo.component.css']
})

(动物园是父母,狮子是孩子)

但是在您的情况下,我只是将子级的宽度和高度设置为100%,例如lion.css:

:host() { width: 100%; height: 100% } 

:host()表示组件的根标记

答案 2 :(得分:0)

在子组件中,您必须将HTML更改为

 <img [width]="width" [height]="height" [src]="name" >
相关问题