No provider for ControlContainer AngularJS2 - html

I am doing a job and I am not getting out of this error 2 days ago I will be posting the html code and TypeScript.
Code Index
<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>
Code 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
</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>
Code 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;
}
}
}
Error
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
I tried in various ways that came from my head, but I did not succeed.
Thank you very much in advance

The [] are missing in
formGroup="usuarioGroup"
It should be
[formGroup]="usuarioGroup"
The former creates an attribute with the string value 'usuarioGroup',
while the later binds the usuarioGroup field of the component to the formGroup property of the FormGroup directive.

Check if you has the ReactiveFormsModule imported in your module

Related

Validating an Angular form with 2 dropdowns

I am learning to code with a portfolio that I made in Angular frontend, Java Spring Boot backend and SQL database. I added dropdowns to some parts of Angular from tables connected to other tables in the database, with tables and models in backend, and with models in frontend.
This works ok with only 1 dropdown in a form, but now I am trying to have 2 dropdowns in the same form and I can not make it so the submit button is valid.
The component is mixed with english and spanish and is the following:
HTML form only:
<div class="card mat-card" class="section1" id="education">
<div id="education-experience" class="font-fluid" style="padding: 20px;">
<div id="education-experience-header">
<i class="fas fa-book-open"></i>
<h2 class="section-header">Educación</h2>
</div>
<div *ngIf="isAdmin">
<h3>Agregar o editar educación
<i class="fa-solid fa-plus add-btn" data-bs-toggle="modal" data-bs-target="#educacionModal"></i>
<br>Modo: {{accion}}
<br>Resetear modo <i class="fa-solid fa-rotate-left" (click)="cancelar()" type="reset"></i>
</h3>
<div class="modal fade" id="educacionModal" tabindex="-1" role="dialog" aria-labelledby="educacionModalLabel">
<div class="modal-dialog modal-xl" role="document" style="width: 100%; max-width: 1500px">
<div class="modal-content">
<div class="modal-header">
<div style="flex-direction: column-start;">
<h3 class="modal-title" id="educacionModalLabel">Modo: {{accion}}</h3>
<p class="modal-subtitle">Cada educación que se agrega, queda primera en la lista.</p>
</div>
</div>
<div class="modal-body">
<form [formGroup]="form" (ngSubmit)="crearEducacion()">
<div class="input-group mb-3">
<label class="input-group-text">Institución</label>
<input formControlName="schoolName" type="text" class="form-control" placeholder="Nombre de la institución"
[ngClass]="{'is-invalid':SchoolName?.errors && SchoolName?.touched, 'is-valid':!SchoolName?.errors && SchoolName?.touched}">
<div *ngIf="SchoolName?.errors && SchoolName?.touched">
<p *ngIf="SchoolName?.hasError('required')" class="text-danger" style="background-color: black;">
Ponga la institución.
</p>
</div>
</div>
<div class="input-group mb-3">
<label class="input-group-text">Título</label>
<input formControlName="title" type="text" class="form-control" placeholder="Título"
[ngClass]="{'is-invalid':Title?.errors && Title?.touched, 'is-valid':!Title?.errors && Title?.touched}">
<div *ngIf="Title?.errors && Title?.touched">
<p *ngIf="Title?.hasError('required')" class="text-danger" style="background-color: black;">
Ponga el título.
</p>
</div>
</div>
<div class="input-group mb-3">
<label class="input-group-text">Logo</label>
<input formControlName="logo" type="text" class="form-control"
placeholder="URL del logo (tiene que estar previamente en alguna página)">
</div>
<div class="row">
<div class="col-lg-3">
<div class="input-group mb-3">
<label class="input-group-text">Fecha de inicio</label>
<input formControlName="startDate" type="date" class="form-control" placeholder="Fecha de inicio"
[ngClass]="{'is-invalid':StartDate?.errors && StartDate?.touched, 'is-valid':!StartDate?.errors && StartDate?.touched}">
<div *ngIf="StartDate?.errors && StartDate?.touched">
<p *ngIf="StartDate?.hasError('required')" class="text-danger" style="background-color: black;">
Ponga la fecha de inicio.
</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="input-group mb-3">
<label class="input-group-text">Fecha de fin</label>
<input formControlName="endDate" type="date" class="form-control" placeholder="Fecha de fin"
[ngClass]="{'is-invalid':EndDate?.errors && EndDate?.touched, 'is-valid':!EndDate?.errors && EndDate?.touched}">
<div *ngIf="EndDate?.errors && EndDate?.touched">
<p *ngIf="EndDate?.hasError('required')" class="text-danger" style="background-color: black;">
Ponga la fecha de fin.
</p>
</div>
</div>
</div>
<div class="col-lg-5">
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text">
Educación actual (poner cualquier fecha en fecha de fin y marcar el checkbox)
<input formControlName="currentEducation" type="checkbox" class="form-check-input"
placeholder="Educación actual">
</label>
</div>
</div>
</div>
</div>
<div class="col-lg-5">
<div class="input-group mb-3">
<label class="input-group-text">Tipo de educación</label>
<select formControlName="educacion_tipo">
<option *ngFor="let educacion_tipo of educacion_tipoLista" [value]="educacion_tipo.id" placeholder="Tipo de educación"
[ngClass]="{'is-invalid':Educacion_tipo?.errors && Educacion_tipo?.touched, 'is-valid':!Educacion_tipo?.errors && Educacion_tipo?.touched}">
{{educacion_tipo.educationType}}
</option>
</select>
<p *ngIf="Educacion_tipo?.hasError('required')" class="text-danger" style="background-color: black;">
Ponga el tipo de educación.
</p>
</div>
</div>
<div class="col-lg-5">
<div class="input-group mb-3">
<label class="input-group-text">Estado de educación</label>
<select formControlName="educacion_estado">
<option *ngFor="let educacion_estado of educacion_estadoLista" [value]="educacion_estado.id" placeholder="Estado de educación"
[ngClass]="{'is-invalid':Educacion_estado?.errors && Educacion_estado?.touched, 'is-valid':!Educacion_estado?.errors && Educacion_estado?.touched}">
{{educacion_estado.educationStatus}}
</option>
</select>
<p *ngIf="Educacion_estado?.hasError('required')" class="text-danger" style="background-color: black;">
Ponga el estado de educación.
</p>
</div>
</div>
<div class="input-group mb-3">
<label class="input-group-text">Descripción</label>
<input formControlName="educationDescription" type="text" class="form-control" placeholder="Descripción"
[ngClass]="{'is-invalid':EducationDescription?.errors && EducationDescription?.touched,
'is-valid':!EducationDescription?.errors && EducationDescription?.touched}">
<div *ngIf="EducationDescription?.errors && EducationDescription?.touched">
<p *ngIf="EducationDescription?.hasError('required')" class="text-danger" style="background-color: black;">
Ponga la descripción.
</p>
</div>
</div>
<div class="d-grip gap-2">
<button type="submit" class="btn btn-success btn-lg" [disabled]="!form.valid" data-bs-dismiss="modal">Aceptar</button>
<button type="reset" class="btn btn-danger btn-lg" (click)="cancelar()" data-bs-dismiss="modal" aria-label="Close">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
TypeScript:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { EducacionEstado } from 'src/app/modelos/educacion-estado.model';
import { EducacionTipo } from 'src/app/modelos/educacion-tipo.model';
import { Educacion } from 'src/app/modelos/educacion.model';
import { EducacionService } from 'src/app/servicios/educacion.service';
import { TokenService } from 'src/app/servicios/token.service';
#Component({
selector: 'app-educacion',
templateUrl: './educacion.component.html',
styleUrls: ['./educacion.component.css']
})
export class EducacionComponent implements OnInit {
educacionLista?:Educacion[];
educacion:Educacion = { id: 0, schoolName: '', title: '', logo: '', startDate: new(Date), endDate: new(Date), educationDescription: '',
currentEducation: false, educacion_tipo: {id: 0, educationType: ''}, educacion_estado:{id: 0, educationStatus: ''},persona: 0 };
accion = 'Agregar';
form: FormGroup;
id: number | undefined;
authority!:string;
isAdmin = false;
educacion_tipo:EducacionTipo = { id: 0, educationType: '' };
educacion_tipoLista?:EducacionTipo[];
educacion_estado:EducacionEstado = { id: 0, educationStatus: '' };
educacion_estadoLista?:EducacionEstado[];
constructor(private educacionService:EducacionService, private fb:FormBuilder, private tokenService: TokenService) {
this.form = this.fb.group({
schoolName: ['',[Validators.required]],
title:['',[Validators.required]],
logo: [''],
startDate: [0,[Validators.required]],
endDate: [0,[Validators.required]],
studiesStatus: ['',[Validators.required]],
educationDescription: ['',[Validators.required]],
currentEducation: false,
educacion_tipo: ['',[Validators.required]],
educacion_estado: ['',[Validators.required]]
})
}
ngOnInit(): void {
this.obtenerEducacion();
this.obtenerEducacionTipo();
this.obtenerEducacionEstado();
this.isAdmin = this.tokenService.isAdmin();
}
obtenerEducacion(){
this.educacionService.obtenerEducacion().subscribe(educacion => {
this.educacionLista=educacion;
}, error => {
console.log(error)
})
}
obtenerEducacionTipo(){
this.educacionService.obtenerEducacionTipo().subscribe(educacion_tipo => {
this.educacion_tipoLista=educacion_tipo;
}, error => {
console.log(error)
});
}
obtenerEducacionEstado(){
this.educacionService.obtenerEducacionEstado().subscribe(educacion_estado => {
this.educacion_estadoLista=educacion_estado;
}, error => {
console.log(error)
});
}
crearEducacion() {
const educacion: Educacion = {
schoolName: this.form.get('schoolName')?.value,
title: this.form.get('title')?.value,
logo: this.form.get('logo')?.value,
startDate: this.form.get('startDate')?.value,
endDate: this.form.get('endDate')?.value,
educationDescription: this.form.get('educationDescription')?.value,
currentEducation: this.form.get('currentEducation')?.value,
educacion_tipo: this.educacion_tipoLista!.find(et=>et.id==this.form.get('educacion_tipo')?.value),
educacion_estado: this.educacion_estadoLista!.find(es=>es.id==this.form.get('educacion_estado')?.value)
}
if(this.id == undefined) {
this.educacionService.crearEducacion(educacion).subscribe(educacion => {
this.obtenerEducacion();
this.form.reset();
}, error => {
console.log(error);
})
} else {
educacion.id = this.id;
this.educacionService.actualizarEducacion(this.id, educacion).subscribe(educacion => {
this.form.reset();
this.accion = 'Agregar';
this.id = undefined;
this.obtenerEducacion();
}, error => {
console.log(error);
})
}
}
borrarEducacion(id: number) {
this.educacionService.borrarEducacion(id).subscribe(educacion =>{
this.obtenerEducacion()
}, error => {
console.log(error);
})
}
actualizarEducacion(educacion: Educacion) {
this.accion = 'Editar educación: ' + educacion.title + ' en ' + educacion.schoolName;
this.id = educacion.id;
this.form.patchValue({
schoolName: educacion.schoolName,
title: educacion.title,
logo: educacion.logo,
startDate: educacion.startDate,
endDate: educacion.endDate,
educationDescription: educacion.educationDescription,
currentEducation: educacion.currentEducation,
educacion_tipo: educacion.educacion_tipo?.id,
educacion_estado: educacion.educacion_estado?.id
})
}
cancelar(){
this.form.reset();
this.accion = 'Agregar';
this.id = undefined;
this.obtenerEducacion();
}
get SchoolName(){
return this.form.get('schoolName');
}
get Title(){
return this.form.get('title');
}
get StartDate(){
return this.form.get('startDate');
}
get EndDate(){
return this.form.get('endDate');
}
get EducationDescription(){
return this.form.get('educationDescription');
}
get Educacion_tipo(){
return this.form.get('educacion_tipo');
}
get Educacion_estado(){
return this.form.get('educacion_estado')
}
}
There is a service for HTTP, models for educacion, educacion_tipo and educacion_estado and JWT for editing. I had educacion_tipo and it worked, but I added educacion_estado and the form will not become valid. Removing validators from HTML and TypeScript also does not work. The only workaround is removing is valid from submit, but I would like to keep that validation in the component.

Populating Dropdown list in html from Database using ViewBag

I am able to get values into ViewBag and then I am passing those values into the HTML page. The Problem I am facing is that once i am passing the value into HTML, I am not able to populate the value into the Dropdown List.
Following is my code for the same:
#using PagedList;
#using PagedList.Mvc;
#model IPagedList<NurseOneStop.SC.NurseProfile>
#{
ViewBag.Title = "People";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="peoplemain-container" ng-controller="connectCtrl">
<div class="row">
<div class="search-box">
#using (Html.BeginForm("People", "Nurse", FormMethod.Get))
{
<div class="j_searchName">
<input class="form-control" name="FirstName" placeholder="Search by FirstName" value="#ViewBag.FilterNurseSearch.FirstName" />
<input type="hidden" name="Connected" placeholder="Search Name" value="#(ViewBag.Connected == true ?"true":"false")" />
</div>
<div class="j_search2">
<center><button type="submit" class="btn btn-primary sb">Search</button></center>
</div>
}
</div>
<div class="search-box">
#using (Html.BeginForm("People", "Nurse", FormMethod.Get))
{
<div class="j_search">
<input class="form-control" name="FirstName" placeholder="Search by FirstName" value="#ViewBag.FilterNurseSearch.FirstName" />
<input type="hidden" name="Connected" placeholder="Search Name" value="#(ViewBag.Connected == true ?"true":"false")" />
</div>
<div class="j_search">
<input class="form-control" name="LastName" placeholder="Search by LastName" value="#ViewBag.FilterNurseSearch.LastName" />
</div>
<div class="j_search">
<input id="pinput" name="JobLocation" class="form-control" type="text" value="#ViewBag.FilterNurseSearch.JobLocation" placeholder="Enter a location">
<input id="Latitude" name="Latitude" type="hidden" value="#ViewBag.FilterNurseSearch.Latitude">
<input id="Longitude" name="Longitude" type="hidden" value="#ViewBag.FilterNurseSearch.Longitude">
</div>
<div class="j_search">
<select class="form-control" name="Profession">
<option value="#ViewBag.Profession" selected>Select Profession</option>
#for (int i = 1; i < ViewBag.Profession.Count + 1; i++)
{
<option value=#i #(ViewBag.FilterNurseSearch.Profession == i ? "selected" : "")>#ViewBag.Profession[i].Text</option>
}
</select>
</div>
<div class="form-group">
#Html.LabelFor(model => model., new { #class = "control-label" })
#Html.DropDownListFor(model => model.ParentProfessionId, (List<SelectListItem>)ViewBag.Profession, new { #class = "form-control" })
#Html.DropDownListFor(model => model.ParentProfessionId, (List<SelectListItem>)TempData["TempModel"], new { #class = "form-control" })
</div>
<div class="j_search2">
<center><button type="submit" class="btn btn-primary sb">Advance Search</button></center>
</div>
}
</div>
</div>
#foreach (var item in Model)
{
<div class="people_container">
<div class="connect_profile"><img src="#(item.ProfileUrl== "" ?"/image/placeholder.jpg" : #item.ProfileUrl)" title="#item.Title #item.FirstName #item.LastName" /></div>
<div class="clear"></div>
<div class="job_box">
<p><b>#item.Title #item.FirstName #item.LastName</b></p>
<p><span>#item.Profession</span></p>
</div>
<div class="job_box_btn">
<button class="details_btn">
#Html.ActionLink("View Nurse", "NurseView", "Nurse", new { NurseId = item.NurseId }, new { #class = "" })
</button>
<button class="details_btn">
<a style="display:#(item.Status==0? "block": "none")" id="connect_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId, 1)">Connect</a>
<a style="display:#(item.Status==1? "block": "none")" id="cancel_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId,3)">Cancel</a>
<a style="display:#(item.Status==2 || item.Status==3? "block": "none")" id="message_#item.NurseId" NurseFriendId="#item.NurseFriendId" href="/Nurse/GetInbox?FromNurseId=#NurseOneStop.WebSite.Models.ApplicationSession.CurrentUser.NurseId&ToNurseId=#item.NurseId&FromRecruiterId=&ToRecruiterId=">Message</a>
<div class="tick-right"><a style="display:#(item.Status==4? "block": "none")" id="accept_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId,2);"> <i class="fa fa-check"></i></a></div>
<div class="tick-wrong"><a style="display:#(item.Status==4? "block": "none")" id="reject_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId,3);"><i class="fa fa-times"></i></a></div>
</button>
</div>
</div>
}
<!--Confirm Modal -->
<div id="confirm" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content cancel-invitemodal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Cancel the Invitation to Connect</h4>
</div>
<div class="modal-body cancel-invitetion">
<h2>Are you sure you want to Cancel the Invitation to Connect</h2>
<div class="cancel-box">
<input type="button" class="btn" ng-click="RequestCancel(SelectedNurseId,3)" value="CANCEL INVITE">
<input type="button" class="btn" ng-click="Cancel()" value="DO NOT CANCEL INVITE">
</div>
</div>
</div>
</div>
</div>
<div class="pagination">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("People", new { page, Connected = ViewBag.Connected, SearchName = ViewBag.SearchName }), PagedListRenderOptions.OnlyShowFivePagesAtATime)
</div>
</div>
#section scripts{
<script>
function initMap() {
var input = document.getElementById('pinput');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function () {
var place = autocomplete.getPlace();
console.log(JSON.stringify(place));
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
var latlong = JSON.parse(JSON.stringify(place.geometry.location));
document.getElementById('Latitude').value = latlong.lat;
document.getElementById('Longitude').value = latlong.lng;
});
}
initMap();
function showhide(id) {
$("ul").hide();
$("#newpost" + id).toggle();
}
$('#pinput').on('input', function () {
document.getElementById('Latitude').value = '';
document.getElementById('Longitude').value = '';
// do your stuff
});
</script>
}
Following is how I am using my controller:
public void DropDown()
{
ProfessionDAL objProfessionDAL = new ProfessionDAL();
Profession objProfession = new Profession();
List<Profession> objProfessionList = new List<Profession>();
SelectListItem objSelect = new SelectListItem { Text = "Select Profession", Value = "", Selected = true };
objProfessionList = objProfessionDAL.GetProfessionList().Results;
var profession = (from kl in objProfessionList
select new SelectListItem
{
Text = kl.ProfessionName,
Value = kl.ProfessionId.ToString(),
Selected = false
}).ToList();
profession.Insert(0, objSelect);
ViewBag.Profession = profession;
}
public ActionResult People(bool Connected, int? page, FilterNurseSearch objFilterNurseSearch)
{
if (ApplicationSession.CurrentUser == null)
{
//redirect
return RedirectToAction("Login", "Account");
}
DropDown();
long NurseId = ApplicationSession.CurrentUser.NurseId;
ViewBag.FilterNurseSearch = objFilterNurseSearch;
Result objResult = objNurseDAL.GetNurses(NurseId, Connected, objFilterNurseSearch);
int pageSize = 12;
int pageNumber = (page ?? 1);
ViewBag.Connected = Connected;
return View(((List<NurseProfile>)objResult.Results).ToPagedList(pageNumber, pageSize));
}
I know I am making a silly mistake which I am not able to catch and henceforth, ask my fellow developers to help me.

How to get the value of dynamically created input in angular

I have created an empty hash map of a 'question' object in angular according to the no. of questions given in the earlier page.Then i am rendering the 'question' objects in the hash map when the page initializes.I want to get the values of the inputs given for each question object when the user clicks 'add paper' button which calls the 'test()' function.What is the best way to do this?I was thinking of using viewChild to get the values,but it returns undefined.Thanks in advance.
Component File
import { Component, OnInit, ViewChild,ElementRef, ViewChildren } from '#angular/core';
import { SharedserviceService } from "../services/sharedservice.service";
#Component({
selector: 'app-admin-paper',
templateUrl: './admin-paper.component.html',
styleUrls: ['./admin-paper.component.css']
})
export class AdminPaperComponent implements OnInit {
public paperID:any;
public noOfQuestions : number ;
public message : any;
public i : number ;
public questionSet = {};
public question0 : any;
#ViewChildren('testchild') testchild :ElementRef;
constructor(private shared : SharedserviceService) { }
ngOnInit() {
this.shared.currentMessage.subscribe((message)=>{
this.message = message;
});
this.paperID = this.message.paperID;
this.noOfQuestions = this.message.noOfQuestions;
for (this.i =0;this.i < this.noOfQuestions;this.i++){
const question = {
'paperID': this.paperID,
'questionID': this.i,
'question': '',
'answers': [],
'correctAnswer':''
};
this.questionSet[this.i] = question;
}
console.log(this.questionSet);
}
test(){
//console.log(this.testchild.nativeElement.value);
for (this.i =0;this.i < this.noOfQuestions;this.i++){
const question = {
'paperID': this.paperID,
'questionID': this.i,
'question': `question${this.i}');`,
'answers': [`question${this.i}answer0`,`question${this.i}answer1`,`question${this.i}answer2`,`question${this.i}answer3`],
'correctAnswer':'vghvhg'
};
console.log(question);
this.questionSet[this.i] = question;
}
console.log("clicked");
console.log(this.questionSet);
}
}
HTML File
<ng-container *ngIf="questionSet" >
<div class="panel panel-widget border-right" *ngFor="let question of questionSet | keyvalue; let i= index;" style="text-align: left; background-color: white; padding: 10px; border-radius: 10px;border-style: solid; border-width: 3px; border-color: #1aa3ff;">
<div class="container">
<div class="row">
<div class="form-group col-md-10">
<label> Question {{question.value.questionID+1}}</label>
<input type="text" class="form-control" #question{{i}} aria-describedby="emailHelp" placeholder="Enter question Here">
</div>
</div>
<div class= "row">
<div class="col-sm-2">
<div class="form-group">
<label>Answer 1</label>
<input type="email" class="form-control" id="question{{i}}answer0" aria-describedby="emailHelp" placeholder="Answer 1">
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label>Answer 2</label>
<input type="email" class="form-control" id="question{{i}}answer1" aria-describedby="emailHelp" placeholder="Answer 2">
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label>Answer 3</label>
<input type="email" class="form-control" id="question{{i}}answer2" aria-describedby="emailHelp" placeholder="Answer 3">
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label>Answer 4</label>
<input type="email" class="form-control" id="question{{i}}answer3" aria-describedby="emailHelp" placeholder="Answer 4">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Correct Answer</label>
<input type="text" class="form-control" aria-describedby="emailHelp" placeholder="Correct Answer">
</div>
</div>
<div class="col-sm-6">
<button type="submit" style="margin-top:6%" (click)="addQuestion($event,question,'new')" class="btn btn-primary mb-2">Add Question</button>
</div>
</div>
<br><br>
</div>
</ng-container>
<button type="button" class="btn btn-primary btn-lg btn-block" (click)="test()">Add Paper</button>
*ngIf="questionSet" always be true because an empty object is a truthy value in js. Convert your ngOnInit like this
ngOnInit() {
this.shared.currentMessage.subscribe((message)=>{
this.message = message;
this.paperID = this.message.paperID;
this.noOfQuestions = this.message.noOfQuestions;
for (let i =0; i < this.noOfQuestions; i++){
const question = {
'paperID': this.paperID,
'questionID': this.i,
'question': '',
'answers': [],
'correctAnswer':''
};
this.questionSet[this.i] = question;
}
console.log(this.questionSet);
});
}

Angular 6 file upload with other form data

I have enter data user details first_name,last_name,phone_number and profile_pic but file is not upload in other form data how can i upload file with other form data??
user-form.component.ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { HttpClient } from '#angular/common/http';
import { UserService } from '../user.service';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';
#Component({
selector: 'user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.scss']
})
export class UserFormComponent {
angForm: FormGroup
router: Router;
constructor(private userservice: UserService, private fb: FormBuilder, private _route: Router) {
this.createForm();
this.router = _route;
}
createForm() {
this.angForm = this.fb.group({
first_name: ['', Validators.required],
last_name: ['', Validators.required],
// email: ['', Validators.required,Validators.email],
email: ['', Validators.compose([Validators.required, Validators.email])],
phone_number: ['', Validators.compose([Validators.required, Validators.maxLength(10)])],
profile_pic:[]
});
}
addUser(first_name, last_name, email, phone_number,profile_pic) {
var data = {
first_name: first_name,
last_name: last_name,
email: email,
phone_number: phone_number,
profile_pic: profile_pic,
}
console.log(data);
// this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; }
// public uploader : FileUploader;
// uploader.onAfterAddingFile = (file) => { file.withCredentials = false; }
this.userservice.addUser(data);
this.router.navigate(['/pages/users/list']); //Redirection path
}
}
user-form.component.html
<div class="row justify-content-center">
<div class="col-lg-8">
<nb-card>
<nb-card-header>Add User</nb-card-header>
<nb-card-body>
<!-- <div [formGroup]="form"> -->
<form [formGroup]="angForm" novalidate>
<div class="row full-name-inputs form-group">
<div class="col-sm-6 input-group">
<input type="text" placeholder="First Name" formControlName="first_name" class="form-control" #firstName/>
</div>
<div *ngIf="angForm.controls['first_name'].invalid && (angForm.controls['first_name'].dirty || angForm.controls['first_name'].touched)" class="alert alert-danger" >
<div *ngIf="angForm.controls['first_name'].errors.required">
First Name is required.
</div>
</div>
<div class="col-sm-6 input-group">
<input type="text" placeholder="Last Name" formControlName="last_name" class="form-control" #lastName/>
</div>
<div *ngIf="angForm.controls['last_name'].invalid && (angForm.controls['last_name'].dirty || angForm.controls['last_name'].touched)" class="alert alert-danger" >
<div *ngIf="angForm.controls['last_name'].errors.required">
Last Name is required.
</div>
</div>
</div>
<div class="form-group input-group">
<input type="email" placeholder="Email" formControlName="email" class="form-control" #email/>
</div>
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)" class="alert alert-danger" >
<div *ngIf="angForm.controls['email'].errors.required">
Email is required.
</div>
<div *ngIf="angForm.controls['email'].errors.email">
Enter valid email.
</div>
</div>
<div class="form-group input-group">
<input type="number" placeholder="Phone Number" formControlName="phone_number" class="form-control" #phoneNumber/>
</div>
<div *ngIf="angForm.controls['phone_number'].invalid && (angForm.controls['phone_number'].dirty || angForm.controls['phone_number'].touched)" class="alert alert-danger" >
<div *ngIf="angForm.controls['phone_number'].errors.required">
Phone Number is required.
</div>
<div *ngIf="angForm.controls['phone_number'].errors.maxLength">
Phone Number must be 10 digits
</div>
</div>
<div class="form-group input-group">
<input type="file" class="form-control file-data" formControlName="profile_pic" #profilePic />
</div>
<div class="input-group">
<!-- <input type="submit" class="btn btn-success btn-rectangle btn-demo ml-auto submit-btn" name="Submit" > -->
<button (click)="addUser(firstName.value, lastName.value,email.value,phoneNumber.value,profilePic.value);" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-success btn-rectangle btn-demo ml-auto submit-btn">Submit</button>
</div>
</form>
<!-- </div> -->
</nb-card-body>
</nb-card>
</div>
</div>
When using form-data to upload file with other form inputs
string and file upload to REST API by form-data. Can anyone please suggests for this? Thanks in advance.
try below code to post data with file upload.
ngOnInit() {
this.uploader.onBuildItemForm = (fileItem: any, form: any) => {
form.append('appNo', this.appNo); //note comma separating key and value
};
}

Angularjs register form not working

I have Angular App, and there is a register form like(Contact-Page with add user) below, but not binding data means (ADD Delete User not working) just displaying the form. Does anyone know how to do it?
View: contact.html
<div class="generic-container" ng-controller="RegCtrl as ctrl">
<div class="panel panel-default">
<div class="panel-heading"><span class="lead">User Registration Form </span></div>
<div class="formcontainer">
<form ng-submit="ctrl.submit()" name="myForm" class="form-horizontal">
<input type="hidden" ng-model="ctrl.user.id" />
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="file">Name</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.username" name="uname" class="username form-control input-sm" placeholder="Enter your name" required ng-minlength="3"/>
<div class="has-error" ng-show="myForm.$dirty">
<span ng-show="myForm.uname.$error.required">This is a required field</span>
<span ng-show="myForm.uname.$error.minlength">Minimum length required is 3</span>
<span ng-show="myForm.uname.$invalid">This field is invalid </span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="file">Address</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.address" class="form-control input-sm" placeholder="Enter your Address. [This field is validation free]"/>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="file">Email</label>
<div class="col-md-7">
<input type="email" ng-model="ctrl.user.email" name="email" class="email form-control input-sm" placeholder="Enter your Email" required/>
<div class="has-error" ng-show="myForm.$dirty">
<span ng-show="myForm.email.$error.required">This is a required field</span>
<span ng-show="myForm.email.$invalid">This field is invalid </span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-actions floatRight">
<input type="submit" value="{{!ctrl.user.id ? 'Add' : 'Update'}}" class="btn btn-primary btn-sm" ng-disabled="myForm.$invalid">
<button type="button" ng-click="ctrl.reset()" class="btn btn-warning btn-sm" ng-disabled="myForm.$pristine">Reset Form</button>
</div>
</div>
</form>
</div>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading"><span class="lead">List of Users </span></div>
<div class="tablecontainer">
<table class="table table-hover">
<thead>
<tr>
<th>ID.</th>
<th>Name</th>
<th>Address</th>
<th>Email</th>
<th width="100">
</tr>
</thead>
<tbody>
<tr ng-repeat="u in ctrl.users">
<td><span ng-bind="u.id"></span></td>
<td><span ng-bind="u.username"></span></td>
<td><span ng-bind="u.address"></span></td>
<td><span ng-bind="u.email"></span></td>
<td>
<button type="button" ng-click="ctrl.edit(u.id)" class="btn btn-success custom-width">Edit</button> <button type="button" ng-click="ctrl.remove(u.id)" class="btn btn-danger custom-width">Remove</button>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Contrller:
angular.module('myApp', [])
.controller('AppController', ['$scope', function($scope) {
var self = this;
self.user={id:null,username:'',address:'',email:''};
self.id = 4;
self.users = [// In future posts, we will get it from server using service
{id:1, username: 'Sam', address: 'NY', email: 'sam#abc.com'},
{id:2, username: 'Tomy', address: 'ALBAMA', email: 'tomy#abc.com'},
{id:3, username: 'kelly', address: 'NEBRASKA', email: 'kelly#abc.com'}
];
self.submit = function() {
if(self.user.id==null){
self.user.id = self.id++;
console.log('Saving New User', self.user);
self.users.push(self.user);//Or send to server, we will do it in when handling services
}else{
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id == self.user.id) {
self.users[i] = self.user;
break;
}
}
console.log('User updated with id ', self.user.id);
}
self.reset();
};
self.edit = function(id){
console.log('id to be edited', id);
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id == id) {
self.user = angular.copy(self.users[i]);
break;
}
}
}
self.remove = function(id){
console.log('id to be deleted', id);
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id == id) {
self.users.splice(i,1);
if(self.user.id==id){//It is shown in form, reset it.
self.reset();
}
break;
}
}
}
self.reset = function(){
self.user={id:null,username:'',address:'',email:''};
$scope.myForm.$setPristine(); //reset Form
}
}]);
app.js
'use strict';
/**
* #ngdoc overview
* #name peopleApp
* #description
* # myApp
*
* Main module of the application.
*/
angular
.module('myApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/', {
templateUrl: 'views/main.html',
controller: 'CarouselDemoCtrl',
controllerAs: 'main'
})
.when('/Portfolio', {
templateUrl: 'views/Portfolio.html',
controller: 'ctrlApp',
controllerAs: 'Portfolio'
})
.when('/photos', {
templateUrl: 'views/photos.html',
controller: 'AlbumCtrl',
controllerAs: 'photos'
})
.when('/tour', {
templateUrl: 'views/tour.html',
controller: 'ctrlTags',
controllerAs: 'tour'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
controllerAs: 'about'
})
.when('/myganesha', {
templateUrl: 'views/myganesha.html',
controller: 'frmController',
controllerAs: 'myganesha'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'RegCtrl',
controllerAs: 'contact'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'loginCtrl',
controllerAs: 'login'
})
.when('/help', {
templateUrl: 'views/help.html',
controller: 'DefaultController',
controllerAs: 'help'
})
.otherwise({
redirectTo: '/'
});
});