[英]how can I include a javascipt code in angular 2+?
This is the HTML code:这是 HTML 代码:
<div id="myNav" class="overlay">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<div class="overlay-content">
<a href="#">About</a>`enter code here`
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
</div>
<h2>Fullscreen Overlay Nav Example</h2>
<p>Click on the element below to open the fullscreen overlay navigation menu.</p>
<p>In this example, the navigation menu will slide in, from left to right:</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ open</span>
where should I include this script tag in angular project for it to work?我应该在 angular 项目中的什么地方包含这个脚本标签才能让它工作?
<script>
function openNav() {
document.getElementById("myNav").style.width = "100%";
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
}
</script>
Accessing the DOM directly isn't a good idea in Angular. You could, in theory, access DOM using methods like document.getElementById()
or document.querySelector()
in the component controller. But don't do it.在 Angular 中直接访问 DOM 不是一个好主意。理论上,您可以在组件 controller 中使用
document.getElementById()
或document.querySelector()
等方法访问 DOM。但不要这样做。
There are numerous other better ways to manipulate the DOM from the controller. One simple and quick way in your case would be to use [style.width.%]
attribute property binding.还有许多其他更好的方法来操作 controller 中的 DOM。在您的情况下,一种简单快捷的方法是使用
[style.width.%]
attribute 属性绑定。 Try the following尝试以下
component.html组件.html
<div [style.width.%]="customWidth" id="myNav" class="overlay">
And in the controller you could do the following在 controller 中,您可以执行以下操作
component.ts组件.ts
export class SampleComponent implements OnInit {
customWidth = 100; // <-- default width percentage
public openNav() {
this.customWidth = 100;
}
public closeNav() {
this.customWidth = 0;
}
ngOnInit() {
}
}
There are many more refined controls provided by Angular to modify the DOM. Angular提供了很多更精细的控件来修改DOM。 For eg, you could use many other CSS units like
[style.width.px]
, [style.width.em]
, [style.width.in]
and so on.例如,您可以使用许多其他 CSS 单位,如
[style.width.px]
、 [style.width.em]
、 [style.width.in]
等。 You could apply multiple styles using ngStyle
.您可以使用
ngStyle
。 For more advanced DOM features, look into Angular Renderer2 .有关更高级的 DOM 功能,请查看 Angular Renderer2 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.