没有ControlContainer AngularJS2的提供者

时间:2017-01-08 14:51:11

标签: html5 forms validation angular webstorm

我正在做一份工作而且我没有摆脱这个错误2天前我将发布html代码和TypeScript。

代码索引

<html>
<head>
  <base href="/angular-21-menu-busca-alteracao-inclusao-remocao-selecao-inc/">
  <title>Angular 2</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="app/css/bootstrap.css">
  <link rel="stylesheet" href="app/css/site.css">
  <!-- 1. Load libraries -->
  <!-- Polyfill(s) for older browsers -->
  <script src="node_modules/core-js/client/shim.min.js"></script>
  <script src="node_modules/zone.js/dist/zone.js"></script>
  <script src="node_modules/reflect-metadata/Reflect.js"></script>
  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <!-- 2. Configure SystemJS -->
  <script src="systemjs.config.js"></script>

  <script src="app/js/jquery-1.12.4.js"></script>
  <script src="app/js/bootstrap.js"></script>
  <script src="app/js/script.js"></script>
  <script src="app/js/web-animations.min.js"></script>

  <script>
    System.import('app').catch(function(err){ console.error(err); });
  </script>
</head>
<!-- 3. Display the application -->
<body>
<angular-app>Loading...</angular-app>
</body>
</html>

代码Html

<h2 class="text-center">Cadastro de Clientes</h2>
<!-- Adicionar  -->
<h4 id="mensagem" class="text-center" [style.color]="getCor()" [style.visibility]="getVisibilidade()">{{mensagem}}</h4>
<!-- Fim adicionar  -->
<div class="container">
   <div class="row">
      <div class="col-xs-12">
         <div *ngIf="aluno">
            <div class="media-list">
               <div class="row">
                  <div class="col-xs-12">
                     <div class="media">

                        <div class="media-body">
                           <form class="form-horizontal" [formGroup]="usuarioGroup" role="form" (ngSubmit)="onSubmit(usuarioGroup.valid)" novalidate>
                              <fieldset [disabled]="isDesabilitado">
                                 <legend>Inf. Básicas</legend>

                                 <div class="form-group form-group-sm">
                                    <label class="col-sm-2 control-label" for="nome">Nome</label>
                                    <div class="col-sm-9">
                                       <input  type="text"
                                               id="nome"
                                               [ngClass]="{'form-control': true, 'input-sm': true, 'submitted': submitted}"
                                               >
                                    </div>

                                     <div class="col-sm-9 col-sm-offset-2">
                                         <div *ngIf="formErrors.nome && submitted" class="alert alert-danger">
                                             {{ formErrors.nome }}
                                         </div>
                                     </div>
                                    <div class="col-sm-1"></div>

                                 </div>
<!--
                                 <div class="form-group form-group-sm">
                                    <label class="control-label col-sm-2">Sexo</label>
                                    <div class="col-sm-10">
                                       <input type="radio" [(ngModel)]="aluno.sexo" name="sexo" value="M"> Masculino
                                    </div>
                                    <div class="col-sm-10 col-sm-offset-2">
                                       <input type="radio" [(ngModel)]="aluno.sexo" name="sexo" value="F"> Feminino
                                       &nbsp;&nbsp;
                                    </div>
                                 </div>

                                 <div class="form-group form-group-sm">
                                    <label class="control-label col-xs-12 col-sm-2" for="sus">Num.SUS</label>
                                    <div class="col-xs-9 col-sm-3">
                                       <input [(ngModel)]="aluno.sus" maxlength="15" name="sus" class="form-control" id="sus">
                                    </div>
                                    <div class="col-xs-3 col-sm-7"></div>
                                 </div>

                              </fieldset>
                              <br/>
                              <fieldset [disabled]="isDesabilitado">
                                 <legend>Endereço</legend>
                                 <div class="form-group form-group-sm">
                                    <label class="col-sm-2 control-label" for="endereco">Logradouro</label>
                                    <div class="col-sm-9">
                                       <input [(ngModel)]="aluno.endereco" name="endereco" class="form-control"
                                              type="text"
                                              id="endereco">
                                    </div>
                                    <div class="col-sm-1"></div>
                                 </div>

                                 <div class="form-group form-group-sm">
                                    <label class="col-sm-2 control-label" for="bairro">Bairro</label>
                                    <div class="col-sm-9">
                                       <input [(ngModel)]="aluno.bairro" name="bairro" class="form-control" type="text"
                                              id="bairro">
                                    </div>
                                    <div class="col-sm-1"></div>
                                 </div>

                                 <div class="form-group form-group-sm">
                                    <label class="col-sm-2 control-label" for="cidade">Cidade</label>
                                    <div class="col-sm-9">
                                       <input [(ngModel)]="aluno.cidade" name="cidade" class="form-control" type="text"
                                              id="cidade">
                                    </div>
                                    <div class="col-sm-1"></div>
                                 </div>

                                 <div class="form-group form-group-sm">
                                    <label class="col-xs-12 col-sm-2 control-label" for="estado">Estado</label>
                                    <div class="col-xs-5 col-sm-2">
                                       <input [(ngModel)]="aluno.estado" maxlength="2" name="estado" class="form-control" type="text"
                                              id="estado">
                                    </div>
                                    <div class="col-xs-7 col-sm-8"></div>
                                 </div>
                                 -->
                              </fieldset>
                           </form>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
            <div class="wrapper">
               <!-- Adicionar  -->
               <button *ngIf="exibirEditar" class="btn btn-primary" (click)="editavel()">
                  <span class="glyphicon glyphicon-edit"></span> Editar
               </button>
               <button *ngIf="exibirAlterar" [disabled]="!f.valid" class="btn btn-primary" (click)="alterar(aluno)">
                  <span class="glyphicon glyphicon-save"></span> Alterar
               </button>
               <button *ngIf="exibirCadastrar" [disabled]="!usuarioGroup.valid" class="btn btn-primary" (click)="cadastrar(aluno)">
                  <span class="glyphicon glyphicon-save"></span> Salvar
               </button>
               <!-- Fim adicionar  -->
               <button class="btn btn-warning" (click)="voltar()">
                  <span class="glyphicon glyphicon-backward"></span> Voltar
               </button>
            </div>
            <br/>
            <br/>
            <br/>
         </div>
      </div>
   </div>
</div>

代码TS

import { Component, OnInit }      from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { AlunoService }           from './aluno.service';
import { Aluno }                  from './aluno';
import { Router }                 from '@angular/router';
import {FormBuilder, FormGroup, Validators}   from "@angular/forms";
import {AutoValida} from "./auto.valida";

interface UsuarioForm {
    nome: string,
    sexo: string,
    endereco: string,
    bairro: string,
    cidade: string,
    estado: string,
    sus: string,
}

@Component({
    selector: 'exibir-aluno',
    templateUrl: 'app/partials/exibir-aluno.component.html',
    styleUrls: ['app/css/exibir-aluno.css']
})

export class ExibirAlunoComponent implements OnInit{
    usuarioForm: UsuarioForm = {nome: '', sexo: '', endereco: '', bairro: '', cidade: '', estado: '', sus: '',};
    usuarioGroup: FormGroup;

    alunos: Aluno[];
    aluno: Aluno = null;
    isDesabilitado: boolean = true;

    // Adicionar campos aqui!
    exibirEditar: boolean = true;
    exibirAlterar: boolean = false;
    mensagem: string = "Esta mensagem será alterada ao exibir!";
    visibilidade: string = "hidden";
    cor: string = "blue";

    exibirCadastrar: boolean = false;

    constructor(private fb: FormBuilder,
                private alunoService:AlunoService,
                private route:ActivatedRoute,
                private router: Router) { }



    ngOnInit():void {
        this.buildForm();
        console.log('executando ngOninit de ExibirAlunoComponent');

        let id = +this.route.snapshot.params['id'];
        console.log('id = ', id);
        // id =  NaN

        if (isNaN(id)) {
            this.novo();
        }
        else {
            this.alunoService.getAluno(id)
                .subscribe(
                    data => {
                        this.aluno = data;
                    },
                    err => {
                        this.mensagem = "Aluno NÃO encontrado! Status:" + err.status;
                        this.cor = "red";
                        this.visibilidade = "visible";
                    }
                );
        }
    }

    novo() {
        this.isDesabilitado = false;
        this.exibirEditar = false;
        this.exibirCadastrar = true;
        this.exibirAlterar = false;
        this.visibilidade = "hidden";

        this.aluno = {
            id: null,
            nome: '',
            sexo: '',
            endereco: '',
            bairro: '',
            cidade: '',
            estado: '',
            sus: '',
        }
    }

    editavel() {
        this.isDesabilitado = false;
        this.exibirEditar = false;
        this.exibirAlterar = true;
        this.visibilidade = "hidden";
        this.exibirCadastrar = false;
    }

    salvo() {
        this.isDesabilitado = true;
        this.exibirEditar = true;
        this.exibirAlterar = false;
        this.exibirCadastrar = false;
    }

    cadastrar(aluno: Aluno) {
        this.salvo();
        this.alunoService.cadastrar(aluno)
            .subscribe(
                resposta => {
                    console.log (resposta);
                    this.mensagem = "Aluno cadastrado com sucesso!";
                    this.cor = "blue";
                    this.visibilidade = "visible";
                },
                err => {
                    this.mensagem = "Aluno NÃO cadastrado! Status:" + err.status;
                    this.cor = "red";
                    this.visibilidade = "visible";
                }
            );
    }

    alterar(aluno: Aluno) {
        this.salvo();
        this.alunoService.atualizar(aluno)
            .subscribe(
                resposta => {
                    console.log (resposta);
                    this.mensagem = "Aluno alterado com sucesso!";
                    this.cor = "blue";
                    this.visibilidade = "visible";
                },
                err => {
                    this.mensagem = "Aluno NÃO alterado! Status:" + err.status;
                    this.cor = "red";
                    this.visibilidade = "visible";
                }
            );
    }

    voltar(): void {
        let link = ['/alunos/exibirtodos'];
        this.router.navigate(link);

    }



    getVisibilidade() {
        return this.visibilidade;
    }

    getCor() {
        return this.cor;
    }
    buildForm(): void {
        this.usuarioGroup = this.fb.group({
            'nome': [this.usuarioForm.nome, [Validators.required, AutoValida.validaNome]],
            'sexo': [this.usuarioForm.sexo, [Validators.required]],
            'sus': [this.usuarioForm.sus, [Validators.required]],
            'endereco': [this.usuarioForm.endereco, [Validators.required]],
            'bairro': [this.usuarioForm.bairro, [Validators.required]],
            'cidade': [this.usuarioForm.cidade, [Validators.required]],
            'estado': [this.usuarioForm.estado, [Validators.required]]
        });

    }
    formErrors = {
        nome: '',
        sexo: '',
        endereco: '',
        bairro: '',
        cidade: '',
        estado: '',
        sus: '',
    }
    submitted: boolean = false;
    onSubmit(){
        this.submitted = true;
        if (!this.usuarioGroup.valid){
            return;
        }
    }
}

错误

   Can't bind to 'formGroup' since it isn't a known property of 'form'. ("                 <div class="media-body">
                           <form class="form-horizontal" [ERROR ->][formGroup]="usuarioGroup" role="form" (ngSubmit)="onSubmit(usuarioGroup.valid)" novalidate>
       "): ExibirAlunoComponent@14:57
No provider for ControlContainer ("                     
                        <div class="media-body">
                           [ERROR ->]<form class="form-horizontal" [formGroup]="usuarioGroup" role="form" (ngSubmit)="onSubmit(usuarioGrou"): ExibirAlunoComponent@14:27 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:
Can't bind to 'formGroup' since it isn't a known property of 'form'. ("                 <div class="media-body">
                           <form class="form-horizontal" [ERROR ->][formGroup]="usuarioGroup" role="form" (ngSubmit)="onSubmit(usuarioGroup.valid)" novalidate>
       "): ExibirAlunoComponent@14:57
No provider for ControlContainer ("                     
                        <div class="media-body">
                           [ERROR ->]<form class="form-horizontal" [formGroup]="usuarioGroup" role="form" (ngSubmit)="onSubmit(usuarioGrou"): ExibirAlunoComponent@14:27

我尝试了各种各样的方式来自我的头脑,但我没有成功。 非常感谢您提前

2 个答案:

答案 0 :(得分:0)

中缺少[]
formGroup="usuarioGroup"

应该是

[formGroup]="usuarioGroup"

前者创建一个字符串值为'usuarioGroup'的属性, 而后者将组件的usuarioGroup字段绑定到formGroup指令的FormGroup属性。

答案 1 :(得分:0)

检查您的模块中是否导入了ReactiveFormsModule