角度6 +显示隐藏元素与ngIf不起作用

时间:2018-05-27 17:11:53

标签: angular

我是棱角分明的新人。我有这样的app.component.html:

<app-login *ngIf="!loggedIn"></app-login>
<section *ngIf="loggedIn" style="background:#EBF0F5;">
    <div class="container">       
        <div class="board">                    
            <msw-navbar ></msw-navbar>      
            <div class="tab-content">
                <!-- Nested view  -->
                <ui-view></ui-view>
            </div>
            <!-- End Content Area -->
        </div>
        <pre>{{ formData | json }}</pre>
    </div>
</section>

我想显示登录页面并在登录后隐藏而没有任何控制或其他东西。 我有login.ts

export class LoginComponent implements OnInit {
  logginIn: boolean = true;
}

在登录点击:

 login() {
    this.logginIn = true;
}
app.component.ts中的

    export class AppComponent implements OnInit {      
    @Input() formData;
    loggedIn: boolean = false;
}

login.html

  <div class="content">
  <form class="login-form">
      <h3 class="form-title">Login to your account</h3>
      <div class="alert alert-danger display-hide" style="display: none;">
        <button class="close" data-close="alert"></button>
        <span> Enter any username and password. </span>
      </div>
      <div class="form-group">
        <div class="input-icon">
          <i class="fa fa-user"></i>
          <input id="userName" name="userName" 
          class="form-control" required
          [(ngModel)]="user.userName"
          autofocus="autofocus" />
        </div>
      </div>
      <div class="form-group">
        <div class="input-icon">
          <i class="fa fa-lock"></i>
          <input id="password" name="password" 
          class="form-control" required 
          [(ngModel)]="user.password"
          type="password"/>
        </div>
      </div>

      <div class="row">
          <div class="col-xs-12">
            <div class="alert alert-danger" 
            *ngIf="securityObject &&
                   !securityObject.isAuthenticated">
              <p>Invalid User Name/Password.</p>
            </div>
          </div>
        </div>
      <br>
      <div class="text-right">
          <button class="btn-lg btn pull-right btnCol" (click)="login()">
              Login
            </button>  
      </div>
    </form>

我应该在app.component中添加什么来从登录组件中获取值true或false?组件如何相互通信?谢谢

1 个答案:

答案 0 :(得分:1)

在app.component.html中:

<app-login *ngIf="!loggedIn" (loggedIn)="isLogged($event)"></app-login>
你的login.component.ts中的

@Output() loggedIn = new EventEmitter<boolean>();

login() {
 this.loggedIn.emit(true);
}
你的app.component.ts中的

isLogged(logged:boolean) {
  this.loggedIn = logged;
}

我希望这会有所帮助