2017-09-06 43 views
1

我开发了一个角度cli项目并获得了许多表单来验证。显示时,我需要在应用根的外侧附加表单验证消息。 我目前的实施情况如下。Angular 2将HTML附加到主体

<app-root class="" _nghost-c0="" ng-version="4.3.4"> 
    <!-- other html content goes here...... --> 
     <form [formGroup]="form"> 
      <label for="name">Name: </label> 
      <input type="text" [formControl]="nameCtrl"/> 
       <div *ngIf="!nameCtrl.valid && nameCtrl.hasError('required')" 
        class="error"><validation-msg>Name is required.</validation-msg></div> 
       <div *ngIf="!nameCtrl.valid && nameCtrl.hasError('badName')" 
        class="error"><validation-msg>Name must start with <tt>pee</tt>.</validation-msg></div> 
     </form> 
    <!-- other html content goes here...... --> 
    </app-root> 

我只需要在html中显示如下所示的错误信息。 validation-msg是具有简单模板的组件。该内容必须附加到应用程序根目录之外。

<app-root class="" _nghost-c0="" ng-version="4.3.4"> 
     <!-- other html content goes here...... --> 
    </app-root> 
    <validation-msg-content> 
     <div>Name is required.</div> 
    </validation-msg-content> 
+0

我不对Angular知之甚少,但你会需要一种“临时解决方法”来实现这一点。 也许在_if_中插入一些脚本标签? –

+0

您基本上需要将数据从一个组件传递到另一个组件。你可以在这里阅读更多关于它的信息https://angular.io/guide/component-interaction – KIA

+0

请检查更新后的问题。它不是关于组件之间共享数据。它是关于将组件模板附加到app-root元素的pout一侧。 –

回答

0

如果是主要组件,那么您将无法做到这一点。但是,如果此表单本身就是一个组件,那么您可以将错误消息发送给包含表单组件的父组件。

您需要在窗体组件中使用@Output,并且可以将错误消息发送到父组件。现在当父组件收到事件时,它可以显示错误消息。

所以表单组件的代码应该是这样的:

import { Component, Input, Output, EventEmitter } from '@angular/core'; 

@Component({ 
    selector: 'myform', 
    templateUrl: './myform.component.html', 
    styleUrls: ['./myform.component.css'] 
}) 

export class MyFormComponent { 
    @Output() sendData:any = new EventEmitter(); 

    validateForm(){ 
     this.sendData.emit({error}); 
    } 

} 

而父组件的HTML

<myform (sendData)="getError($event)"></myform> 

现在,您可以定义getError方法:

getError(event:Event){ 
    //Do whatever you want 
} 
+0

请检查编辑的问题。这不是传递给其他组件的数据。它是关于在app-root元素旁边添加html的。 –

+0

如果'app-root'是主'appComponent',那么'validation-msg-content'必须是另一个模块。我不确定你是否可以在两者之间进行沟通。 eassy的解决方案是将“validation-msg-content”移动到“app-root”中,并为表单创建另一个“组件”。 – Rajan471

+0

请检查ng-bootstrap.github.io/#/components/popover/examples正文部分的追加弹出窗口。我需要将我的信息添加到身体。 –