@HostBinding从子组件Angular 4中禁用类

时间:2017-11-15 15:47:56

标签: javascript html css angular

我有一个角色应用程序,用户登录和注销。我在用户登录之前显示欢迎页面作为主页。我想仅在欢迎页面上启用背景图像。用户登录后,背景图像必须消失。当用户退出时,他将被重定向到欢迎页面,该页面必须再次显示背景图像。

我尝试通过将选择器重命名为'body'来在app.component.ts中使用@HostBinding。

app.component.ts

import {Component, HostBinding, Input} from '@angular/core';
import {InputMask} from "primeng/primeng";

@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  path = '../assets/img/AvayaHome.jpg';
  title = 'app';
  toggleClass = true;
  @HostBinding('class.bodyClass') isWelcomePage = this.toggleClass;
}

这是我的CSS。

app.component.css

.bodyClass  {
    background-image: url("../assets/img/AvayaHome.jpg");
}

这是我的index.html

<!doctype html>
<html lang="en">
<head>
 <title> Something </title>
</head>
<body class="bodyClass">

    <app-welcome-page></app-welcome-page>

</body>
</html>

我通过将toggleClass指定为true来为bodyClass启用css样式。一旦用户登录,我将从子组件更改toggleClass(在app.component.ts中)的值。

这是我的login.component.ts

onLogin() {
    console.log('onLogin() invoked:', this._email, ':' , this.password);
    if (this._email == null || this.password == null) {
      this.errorMessage = 'All fields are required';
      return;
    }
    this.errorMessage = null;
    this.loginservice.authenticate(this._email, this.password);
    this.appComponent.toggleClass = true;
    this.router.navigate(['/dashboard']);
  }

当用户登录为FALSE时,toggleClass的值会更改。但我仍然看到背景图片。不确定我做错了什么。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:1)

举个例子,我们来看看这段代码:

var toggleClass = false;
var isWelcomePage = toggleClass;

console.log(isWelcomePage); // prints true

很酷,一切都按预期工作。

十秒钟后......

一些用户登录:

toggleClass = true;

console.log(isWelcomePage); // prints false

为什么没有改变???

如果您打开任何有关javascript的文档或任何书籍,您可以阅读一条主要规则:

基元总是不可变的。

当我们使用=将toggleClass变量分配给isWelcomePage变量时,我们将值复制到新变量,因为基元是按值复制的。

解决方案1:

直接更改isWelcomePage属性

onLogin() {
  ...
  this.appComponent.isWelcomePage = true;
  ...
}

解决方案2

定义getter

@HostBinding('class.bodyClass')
get isWelcomePage() {
  return this.toggleClass;
}

答案 1 :(得分:0)

如果要动态显示和隐藏背景,则应使用带ngClass

的条件类

您可以在此处详细了解NgClass

在你的情况下,它将是

<div [ngClass]="{'bodyClass': isWelcomePage}">    
    ...
</div>

然后bodyClass css类只会应用 IF isWelcomePagetrue,如果它是false它将不适用且图片获胜不显示。

编辑:

根据要求,提供了一个工作示例:Plunkr

答案 2 :(得分:0)

使用if和else创建函数;

if (user is login) {
  document.body.classList.add('bodyClass');
} else {
  document.body.classList.remove('bodyClass');
}

在需要时调用该函数,logIn logOut

答案 3 :(得分:-1)

Hostbinding仅在您的案例标记中将东西绑定到主机标记。

因此,如果你想操纵body标签,你必须使用组件中的plan javascript或者在主体中创建一个组件。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class StopWatch implements ActionListener {

    JLabel jlab;
    long start;  // holds the start time in milliseconds

    StopWatch() {
        // Create a new JFrame Container.
        JFrame jfrm = new JFrame("A Simple StopWatch");

        // Specify the FlowLayout for the layout manager.
        jfrm.setLayout(new FlowLayout());

        // Give the frame an initial size.
        jfrm.setSize(230,90);

        // Terminates the program when the user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Make two buttons
        JButton jbtnStart = new JButton("Start");
        JButton jbtnStop = new JButton("Stop");

        // Add action listeners. 
        jbtnStart.addActionListener(this);
        jbtnStop.addActionListener(this);

        // Add the buttons to the content pane
        jfrm.add(jbtnStart); 
        jfrm.add(jbtnStop);

        // Create a text-based label
        jlab = new JLabel("Press Start to begin timing.");

        // Add the label
        jfrm.add(jlab);

        jfrm.setVisible(true);

    }

    // Handle button events
    public void actionPerformed(ActionEvent ae) {
        Calendar cal = Calendar.getInstance();  // get current system time

        if (ae.getActionCommand().equals("Start")) { 
            start = cal.getTimeInMillis();
            jlab.setText("Stopwatch is Running...");
        }

        else
            // Compute the elapsed time.
            jlab.setText("Elapsed time is "+(double)(cal.getTimeInMillis() - start)/1000);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
        public void run() { new StopWatch(); }
        });
    }

}