我正在使用flexLayout模块(在https://github.com/angular/flex-layout中查看https://alligator.io/angular/flex-layout/中的更多信息)在我的Angular应用程序中构建响应div,我想从我的Angular Component设置fxFlex属性的值。 component.ts中的代码:
const nav = document.getElementById('nav2'); nav.setAttribute('fxFlex', '5%');
html页面中的代码:
<div fxLayout>
<div id="nav2" fxFlex="25%" class="col-md-2.5 bg-white p-1">hello</div>
<div id="nav1">word</div></div>
代码通常应该将布局大小更改为5%,但事实并非如此,当我检查页面时,我发现属性已更改但布局仍然相同,奇怪的是当我在html代码中手动更改它时5%,我得到了我想要的结果。
我正在使用Angular 6和Typescript 3.1.1
如果有任何建议,请不要犹豫。
谢谢 !
代码通常应该将布局大小更改为5%
不,不应该。
Angular指令用于Typescript或预构建上下文中。
当你写作
document.getElementById('nav2'); nav.setAttribute('fxFlex', '5%')
您指示从Typescript编译的Javascript(在后构建上下文中)以获取元素并向您的属性添加Angular指令。
问题是,代码已经编译好了,所以你不能将打字稿添加到Javascript中,否则你必须再次编译它(我甚至不确定你能做到这一点)。
我建议你在使用前了解角度特征及其工作原理。另外,如果您希望某人提供适合您案例的解决方案,请考虑发布Minimal, Complete, and Verifiable example。
在angular中,您需要动态地使用renderer2来setAttribute。
例:
HTML
<div #myDiv id="nav2" fxFlex="25%" class="col-md-2.5 bg-white p-1"></div>
component.ts
import {ElementRef,Renderer2} from '@angular/core';
...
export class MyComponent implements AfterViewInit {
@ViewChild('myDiv') el:ElementRef; // get the refernce of dom element.
constructor(private rd: Renderer2) {}
ngAfterViewInit() {
// Update dom after view initialized.
this.renderer2.setAttribute(this.el.nativeElement, "fxFlex", "5%");
}
}