Проблема с родительским общением ребенка в угловых 6 - PullRequest
0 голосов
/ 02 октября 2018

У меня проблема с связью родитель / ребенок в angular 6, код работает.Однако я получаю ошибку в карме.См. Ниже:

Failed: Template parse errors:
Can't bind to 'choices' since it isn't a known property of 'app-display-show-choices'.
1. If 'app-display-show-choices' is an Angular component and it has 'choices' input, then verify that it is part of this module.
2. If 'app-display-show-choices' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
    <div *ngSwitchCase="'menu'">
      <app-display-show-choices      
       [ERROR ->][choices]="displayView.choices"
       (nextView)="onNextView($event)"
       >
"): ng:///DynamicTestModule/DisplayViewComponent.html@5:7
'app-display-show-choices' is not a known element:
1. If 'app-display-show-choices' is an Angular component, then verify that it is part of this module.
2. If 'app-display-show-choices' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
  <div [ngSwitch]="displayView.type" >
    <div *ngSwitchCase="'menu'">
      [ERROR ->]<app-display-show-choices      
       [choices]="displayView.choices"
       (nextView)="onNextView("): ng:///DynamicTestModule/DisplayViewComponent.html@4:6
Can't bind to 'choices' since it isn't a known property of 'app-display-show-choices'.
1. If 'app-display-show-choices' is an Angular component and it has 'choices' input, then verify that it is part of this module.
2. If 'app-display-show-choices' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
      <div *ngSwitchCase="'choice'">
          <app-display-show-choices         
           [ERROR ->][choices]="displayView.choices"
           (nextView)="onNextView($event)"
           >
"): ng:///DynamicTestModule/DisplayViewComponent.html@12:11
'app-display-show-choices' is not a known element:
1. If 'app-display-show-choices' is an Angular component, then verify that it is part of this module.
2. If 'app-display-show-choices' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
      </div>
      <div *ngSwitchCase="'choice'">
          [ERROR ->]<app-display-show-choices         
           [choices]="displayView.choices"
           (nextView)=""): ng:///DynamicTestModule/DisplayViewComponent.html@11:10

Родительский компонент:

import { Component, Input, OnInit, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
import { DisplayView } from '../../model/display-view.model';
import { Choice } from '../../model/choice.model';

@Component({
  selector: 'app-display-view',
  templateUrl: './display-view.component.html',
  styleUrls: ['./display-view.component.css']
})
export class DisplayViewComponent implements OnChanges, OnInit {

  @Input() displayView: DisplayView;
  choices: [Choice];
  @Output() nextView = new EventEmitter<number>();


  @Input() currentView: number;
  hidden: boolean;

  constructor() {
    this.hidden = false;
  }

  ngOnInit() {
    this.hidden = !this.displayView.isFirst;
  }

  ngOnChanges(changes: SimpleChanges): void {
    if ( this.currentView !== this.displayView.id) {
      this.hidden = true;
    } else {
      this.hidden = false;
    }
  }

  onNextView(nextView: number) {
    if ( nextView !== this.displayView.id) {
      this.hidden = true;
    } else {
      this.hidden = false;
    }
    this.nextView.emit(nextView);
  }

}

parent html:

<div [hidden]="hidden">
  <h1>{{displayView.title}}</h1>
  <div [ngSwitch]="displayView.type" >
    <div *ngSwitchCase="'menu'">
      <app-display-show-choices      
       [choices]="displayView.choices"
       (nextView)="onNextView($event)"
       >
      </app-display-show-choices>
      </div>
      <div *ngSwitchCase="'choice'">
          <app-display-show-choices         
           [choices]="displayView.choices"
           (nextView)="onNextView($event)"
           >
          </app-display-show-choices>
    </div>
</div>

Дочерний компонент:

import { Component, Input, OnInit, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
import { Choice } from '../../model/choice.model';

@Component({
  selector: 'app-display-show-choices',
  templateUrl: './display-show-choices.component.html',
  styleUrls: ['./display-show-choices.component.css']
})
export class DisplayShowChoicesComponent implements OnInit {
  @Input() choices: [Choice];
  @Output() nextView = new EventEmitter<number>();
  clicked: number;

  constructor() {  }

  ngOnInit() {
  }

  onClick(choice: Choice) {
    this.clicked = choice.value;
    this.nextView.emit(choice.nextQuestion);
  }

}

App.module.ts: </p> <pre><code>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { DisplayMainComponent } from './display/component/display-main/display-main.component'; import { DisplayShowChoicesComponent } from './display/component/display-show-choices/display-show-choices.component'; import { TerminalUserLogonComponent } from './display/component/terminal-user-logon/terminal-user-logon.component'; import { DisplayViewComponent } from './display/component/display-view/display-view.component'; @NgModule({ declarations: [ AppComponent, DisplayMainComponent, DisplayShowChoicesComponent, TerminalUserLogonComponent, DisplayViewComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

display-view.model.ts: </p> <pre><code>import { Choice } from './choice.model'; export class DisplayView { id: number; title: string; type: string; public isFirst: boolean; public choices: Choice[]; constructor(values: Object = {}) { Object.assign(this, values); } }

Возможно, это что-то довольно глупое, так как я только начинаю с angular. В проекте у меня есть другие родительские дочерние комбинации, которые являются окей.Пожалуйста, помогите мне, что я делаю не так?

Ответы [ 2 ]

0 голосов
/ 03 октября 2018

Я нашел проблему, вызвавшую эту ошибку.В файле спецификации первого родительского компонента отсутствовали импорта HttpClientModule и BrowserModule.Добавив их, он решил ошибку.Однако я до сих пор не понимаю, почему такая ошибка возникает из-за отсутствия этих компонентов в основном файле спецификации тестирования родительского компонента.

0 голосов
/ 02 октября 2018

Вы должны убедиться, что DisplayShowChoicesComponent находится в разделе declaration вашего соответствующего файла .modules, который предоставляет ваш DisplayViewComponent.

Примером базового HomeComponent является:

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})

Следующее, о чем вам нужно беспокоиться, это ввод @Input() choices: [Choice];.Я не знаю этот синтаксис.Можете ли вы попробовать

@Input() choices: Choice[];

вместо этого?То же самое в DisplayViewComponent choices: [Choice]; - попробуйте choices: Choice[]; вместо.

...