问题描述
我正在Angular 4中使用具有jQuery功能的选项卡式表单工作.我的选项卡式表单可以使用,但是我注意到我必须单击两次选项卡按钮"才能响应.以下是代码段:
Am working with a Tabbed Form with jQuery Functionality in Angular 4. My Tabbed Form works but I noticed I have to click the Tab Button twice before it responds. Below is the snippet:
TS
declare var jquery: any;
declare var $: any;
export class AppComponent {
title = 'Angular App';
toggleEvent() {
$('.toggle').on('click', function() {
$('.container').stop().addClass('active');
});
$('.close').on('click', function() {
$('.container').stop().removeClass('active');
});
}
}
HTML
<div class="card alt" (click)="toggleEvent()">
..
..
</div>
所以,您知道,我已经在Angular 4中添加了jQuery功能,因为我只是试图将Bootstrap(HTML,CSS,JS)应用程序引入Angular 4中,以使我的Tabbed Form正常工作完全可以自举.
So you know, I have added jQuery functionality to my Angular 4, since am just trying to bring in a Bootstrap (HTML, CSS, JS) App into Angular 4, so as to make my Tabbed Form work as it is working perfectly in bootstrap.
但是为什么我必须两次单击"Tab按钮"才能起作用?我已经检查过,但不知道这里缺少什么.
But why do I have to click the Tab Button twice before it works? I have checked and I do not know what am missing here.
推荐答案
好的.我已经弄清楚了,我认为发布我使用的内容将对很多人有所帮助.我弄清楚了第一次点击的初始化,第二次点击了.为了更好地解决此问题,我使用了Angular ngOnInit()
生命周期挂钩.我没有创建新的click事件,而是将jQuery包裹在ngOnInit()
内,使得TS文件变为:
Okay. I have figured it out and I think posting what I used will help so many people. I figured out the first click initialises and the second takes the action. To better solve that, I used Angular ngOnInit()
lifecycle hook. Instead of creating a new click event, I wrapped the jQuery inside ngOnInit()
such that the TS file becomes:
import { Component, OnInit } from '@angular/core';
declare var jquery: any;
declare var $: any;
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor() { }
ngOnInit() {
$('.toggle').on('click', function() {
$('.container').stop().addClass('active');
});
$('.close').on('click', function() {
$('.container').stop().removeClass('active');
});
}
}
使用此方法,您无需在HTML文件中添加任何点击事件. HTML变成:
With this you do not need to add any click event into your HTML file. HTML becomes:
<div class="card alt">
..
..
</div>
ngOnInit()
在Angular首先显示数据绑定属性并设置指令/组件的输入属性后初始化指令/组件,这将使该功能在页面加载后立即起作用.
ngOnInit()
Initializes the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties, which will make this work immediately the page is loaded.
这篇关于为什么我必须单击"Tab"按钮两次才能响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!