2017-06-19 31 views
0

我有一个简单的文本,这是一个超链接,点击后,它只是打开一个div与fadeIn属性。我已经在我的angular-cli项目中使用了jQuery。但我已经明白,与角度jQuery组合是不可取的。Angular 4(点击)改变另一个元素的类,而不使用jQuery

dashboard.html

<div class="groupMembersPopup" #myname> 
    ........ group is selected from list in this div and binding it to selectGroupName var 
</div> 
<div class="selectPostTo cf"> 
    <label>Post to</label> 
    <a class="selectPostType" (click)="loadPostGroups($event)">{{selectGroupName}}</a> 
</div> 
<div class="overlayPopup1"></div> 

dashboard.ts

@ViewChild('myname') input; 
constructor(private _elementRef: ElementRef){} 
ngOnInit() { 
    let el = this._elementRef.nativeElement; 
    let t = 
    this._elementRef.nativeElement.querySelector('groupMembersPopup'); 
    console.log(t); 
    } 
loadPostGroups(event) { 
    this.startGroup = 0; 
    this.endGroup = 100; 
    this.group_list = []; 
    this.getUserGroups(this.startGroup, this.endGroup); 
    } 

main.js

if ($(".groupMembersPopup").length) { 
     $('.selectPostType').click(function() { 
     $('.groupMembersPopup').addClass('show'); 
     $('.overlayPopup1').fadeIn(); 
     return false; 
     }); 
     $('.overlayPopup1, .groupMembersPopup .btnRemove').click(function() { 
     $('.groupMembersPopup').removeClass('show'); 
     $('.overlayPopup1').fadeOut(); 
     return false; 
     }); 
    } 

我有含在angular-cli.json文件中的脚本中填入我的main.js文件。 Uptil现在我正在以这种方式使用jQuery。 如何在打字稿内转换我的jQuery代码。 我有它,发现可以使用Elementref。尝试过,但无法弄清楚。

+0

你能请张贴在那里你使用'ElementRef'代码的两种方式? – Abrar

回答

3

使用`ngClass`

要添加/在角去除类,它的建议使用所提供的模板语法。

你可以有这样的事情:

模板

<button (click)="shouldShow = !shouldShow"> Show/Hide </button> 
<label [ngClass]="{show: shouldShow, hide: !shouldShow}"> ... </label> 

组件

// Make sure to add the variable in the component 
public shouldShow = true; 

标签将显示/隐藏CSS类之间切换为shouldShow从012开始变化到false

要获得进/出一个简单的褪色,您可以添加这个CSS:

.show { 
    opacity: 1; 
    transition: opacity 1s; 
} 

.hide { 
    opacity: 0; 
    transition: opacity 1s; 
} 

使用`ViewChild`

另一种方法是使用@ViewChild获取该元素参考然后手动添加/删除css类,如下所示:

模板:

<button (click)="showOrHideManually()"> Show/Hide manually </button> 
<label #myLabel> SOME TEXT BLABLA </label> 

组件:

export class App { 
    public shouldShow = true; 
    @ViewChild("myLabel") lab; 

    showOrHideManually() { 
    this.shouldShow = !this.shouldShow; 
    if(this.shouldShow) { 
     this.lab.nativeElement.classList.add("show"); 
     this.lab.nativeElement.classList.remove("hide"); 
    } else { 
     this.lab.nativeElement.classList.add("hide"); 
     this.lab.nativeElement.classList.remove("show"); 
    } 
    } 
} 

这里是一个PLUNKER用做

+0

淡入和淡出效果如何?我首先想到了上述解决方案,但我需要jQuery fadein和fadeout方法,这就是为什么我继续使用jquery,但现在它正在为我创建问题。 – shahakshay94

+0

'class =“”'如果语句更容易改变多个样式并且代码看起来更整齐 – mast3rd3mon

+1

@ shahakshay94'fadeIn/fadeOut'是jQuery特定的动画。你需要重新实现它们要么使用普通的CSS 3或角动画 –

相关问题