有没有一种角度的方法:document.getElementById(id).style.display = "none" ;



我有一个id为1的div。我试图动态地将显示设置为none。有没有一种Angular的方法来做这件事。目前,我正在使用香草javascript。我问动态地做这个,因为将有超过60div将从一个数组创建。

在我的html

<div *ngFor="let item of items; i = index;">
<div id={{i}} (click)=hideDiv()></div> 
</div>

In my method

hideDiv() {
return document.getElementById('1').style.display = "none";
}

这是有效的,但我正在寻找做上面的Angular的方式。

这是建议我使用@ViewChild。这是我所改变的。我不能使用模板引用变量作为htmldiv是动态创建的。除非有人能让我知道如何动态地创建模板变量。虽然我不认为可以用循环来创建模板变量

@ViewChild('imgId', { static: true }) elementRef: ElementRef<HTMLDivElement>;
imgId: string;

然后在方法中我有:

this.imgId = event.path[0].attributes[1].value;
this.elementRef.nativeElement.style.display = "none";

event.path [0] .attributes[1]。Value获取图像的id。当我对它进行控制台日志时,imgId会显示。它仍然没有将div上的显示改为none。我也得到了错误:无法读取未定义的属性(正在读取'nativeElement')

是的,你可以使用Angular中的ViewChild查询来做到这一点。在组件中,像这样定义一个查询:

@ViewChild('#1') elementRef: ElementRef<HTMLDivElement>;

在组件中实现afterviewit接口,并在其中使用:

this.elementRef.nativeElement.style.display = "none";

您可以简单地使用ngIf

<组件/strong>

shouldDisplay: boolean = true;
hide(): void {
this.shouldDisplay = false;
}
show(): void {
this.shouldDisplay = true;
}

<button (click)="hide()">Hide</button>
<button (click)="show()">Show</button>
<div *ngIf="shouldDisplay">this is the content</div>

下面是工作示例

这是Angular的方式:模板

<div *ngIf="showMe"></div>

<div [hidden]="!showMe"></div>

打印稿:

showMe: boolean;
hideDiv() {
this.showMe = false;
}

对于你不知道有多少动态项目,最好的方法是添加一个指令来为你存储和调整它们:

@Directive({ selector: '[hide-me]' })
export class HideDirective {
@Input() id!: string;
@HostBinding('style.display')
shouldShow: string = '';
}

然后在你的组件中通过ID:

@Component({
selector: 'my-app',
styleUrls: ['./app.component.css'],
template: `
<div *ngFor="let item of items; let index = index;">
<div hide-me id="{{index}}" (click)="hideDiv(index)">Some value</div> 
</div>
`,
})
export class AppComponent {
@ViewChildren(HideDirective) hideDirectives!: QueryList<HideDirective>;
items = [null, null, null];
hideDiv(id: number) {
this.hideDirectives.find((p) => p.id === id.toString()).shouldShow = 'none';
}
}

Stackblitz: https://stackblitz.com/edit/angular-ivy-pnrdhv?file=src/app/app.component.ts

angular官方示例:https://stackblitz.com/edit/angular-ivy-pnrdhv?file=src/app/app.component.ts

如何使用像这样的模板变量将div引用直接传递给Dom中的hideDiv方法呢?

<div *ngFor="let item of items; i = index;">
<div #divElement (click)=hideDiv(divElement)></div> 

在你的hidediv方法中你可以直接访问元素

hideDiv(div) { div.style.display = "none";}

这是一个Stackblitz的例子https://stackblitz.com/edit/angular-ivy-w1s3jl

有很多方法可以做到这一点,但在我看来,这是一个简单的解决方案,可以用更少的代码实现您的目标。

p:总是建议使用angular Renderer2来操作Dom元素。这个服务有setStyle方法,你可以在你的代码中使用。

相关内容

最新更新