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: '/'
});
});
Related
I am new to angular, currently I am looking checkboxes in angular , I have three checkboxes and I have to show checked or unchecked checkboxes in UI.
I am getting enabled/disabled from json , I need to show if am getting enabled means checkbox should be checked and disabled means unchecked checkbox.
This is what am trying in html
<form [formGroup]="portFilterGroup">
<div class="form-group row">
<div class="col-md-4 text-left" id="email">
<label for="email"><input type="checkbox" (change)="onChecked($event)" formcontrolName="emailData" value="{{emailData}}" [checked]="isChecked" >
<b>Email(POP3, IMAP, SMTP)</b></label>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="ftp">
<label for="ftp"><input type="checkbox" formcontrolName="ftpData" [checked]="isChecked" value="{{ftpData}}"> <b>FTP</b></label>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="http">
<label for="http"><input type="checkbox" formcontrolName="httpData"
[checked]="isChecked"> <b>HTTP</b></label>
</div>
</div>
</form>
typescript file
portFilterForm(){
this.portFilterGroup = this.fb.group({
emailData: new FormControl(''),
ftpData: new FormControl(''),
httpData: new FormControl('')
})
}
onChecked(e){
console.log("e", e.target)
if (e.target == 'enabled'){
this.isChecked = true;
}
else{
this.isChecked = false;
}
}
gettingData(){
this.httpClient.get("assets/json/data.json").subscribe((data:any) =>{
console.log(data);
this.emailData = this.onChecked(data.email)
this.httpData = this.onChecked(data.http)
})
}
and the json file be
{
"email": "enabled",
"ftp": "disabled",
"http": "enabled"
}
this is the code am trying, but am not get the expecting output(enabled means checked and disabled means unchecked) can anyone help me to this?
Ok so you can use the angular way read here
html
<form [formGroup]="portFilterGroup">
<div class="form-group row">
<div class="col-md-4 text-left" id="email">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['emailData']"
/> <b>Email(POP3, IMAP, SMTP)</b></label
>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="ftp">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['ftpData']"
/> <b>FTP</b></label
>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="http">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['ftpData']"
/> <b>HTTP</b></label
>
</div>
</div>
</form>
{{ portFilterGroup.value | json }}
<button (click)="gettingData()">submit</button>
ts file
import { Component } from '#angular/core';
import { FormControl, FormGroup, FormBuilder, FormArray } from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular 6';
portFilterGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.portFilterForm();
}
portFilterForm() {
this.portFilterGroup = this.fb.group({
emailData: new FormControl(false),
ftpData: new FormControl(false),
httpData: new FormControl(false),
});
}
gettingData() {
console.log(this.portFilterGroup.value);
// this.httpClient.get('assets/json/data.json').subscribe((data: any) => {
// console.log(data);
// this.emailData = this.onChecked(data.email);
// this.httpData = this.onChecked(data.http);
// });
}
}
stackblitz
I'm trying to verify a form that's inside a form.
The idea is to create a user's html page with the option to create a contact list.
My goal is to verify both forms with one click on the 'Save User Profile' button.
My question is How to verify the validion of the inner form inside the main form?
NO BOOTSTRAP AND OTHERS.
Main form:
HTML:
<div class="container"
style="width: 60%;">
<h5>User Profile</h5>
<div>
<form (ngSubmit)="onSubmit()"
#f=ngForm>
<!-- Name -->
<div class="column">
<label for="name"
style="margin-left: 5px;">Name</label><br>
<input type="text"
[(ngModel)]="user.name"
name="name"
id="name"
required
minlength="2"
maxlength="30"
#n="ngModel">
<p *ngIf="!n.valid && n.touched"
style="color: red;"> Please insert a name with 2-30 chars</p>
</div>
<!-- Organization -->
<div class="column">
<label for="orga"
style="margin-left: 5px;">Organization</label><br>
<input type="text"
[(ngModel)]="user.organization"
name="orga"
id="orga">
</div>
<br><br><br><br><br>
<h5>Contact Information</h5>
<div class="box">
<app-user-card *ngFor="let c of contacts; let i = index"
[id]="i"
[user]="user"></app-user-card>
<br><br>
</div>
<button type="button"
class="btn-add"
(click)="addContact()">Add Contact</button>
<button class="btn-save"
type="submit"
[disabled]="!f.valid">Save User Profile
</button>
</form>
</div>
TS:
export class UsersListComponent implements OnInit {
users: User[] = []
user: User = {
name: '',
organization: '',
contacts: []
}
id: number
contacts: Contact[] = []
contact: Contact = {
id: 0,
type: '',
label: '',
contact: ''
}
constructor() { }
ngOnInit(): void {
this.user.contacts = this.contacts
}
addContact() {
this.contacts.push(new Contact(this.id, this.contact.type, this.contact.label, this.contact.contact))
}
onSubmit() {
/* Upgrade option: Check if a user exists on the system and view his contacts*/
this.users.push(new User(this.user.name, this.user.organization, this.contacts))
console.log(this.users);
}
}
inner form:
HTML:
<div class="card">
<form #f = "ngForm">
<div class="column">
<label for="contactType">Type of Contact</label><br>
<select id="contactType"
[(ngModel)]=contact.type
name="cotactType"
style="width: 95%;"
required>
<option value="email">Email</option>
<option value="phone">Phone</option>
</select>
</div>
<div class="column">
<label for="label">Contact Label</label><br>
<input type="text"
[(ngModel)]="contact.label"
id="label"
name="lable"
style="width: 95%;"
required
minlength="2"
maxlength="20"
#l>
<p *ngIf="!l.valid && l.touched"
style="color: red;">Label is required!</p>
</div>
<div>
<label for="contact"
style="margin-left: 5px;">Email/Phon No.</label><br>
<input type="text"
[(ngModel)]=contact.contact
required
id="contact"
name="contact"
style="width: 98%;"
#c>
<p *ngIf="!c.valid && c.touched"
style="color: red;">Email/Phon No is required!</p>
</div>
<button type="button"
class="btn-remove"
style="left: 69%;position: relative;">Remove</button>
</form>
TS:
#Component({
selector: 'app-user-card',
templateUrl: './user-card.component.html',
styleUrls: ['./user-card.component.css']
})
export class UserCardComponent implements OnInit {
contact: Contact = {
id: 0,
type: '',
label: '',
contact: ''
}
#ViewChild("f") contactDetails: NgForm
#Input() id: number
constructor() { }
ngOnInit(): void {}
}
i have created a form for saving and the saved data will be displayed in the datatable at the same page. Datatable rerender() works fine with submission. but on edit rerender() showing "this.dtElement" undefined..
manage-templates.component.ts
import { Component, OnInit, ViewEncapsulation, AfterViewInit, OnDestroy, ViewChild } from '#angular/core';
import { HttpClient, HttpResponse } from '#angular/common/http';
import { FormBuilder, FormGroup, Validators, FormControl } from '#angular/forms';
import { NotifierService } from 'angular-notifier';
import { emailTemplatesService } from '../email-templates.service';
import { Globals } from '../../app.global';
import { Subject } from 'rxjs';
import { DataTableDirective } from 'angular-datatables';
import { Router } from '#angular/router';
class Template {
template_id: string;
template_name: string;
template_desc: string;
template_status: boolean;
}
class DataTablesResponse {
data: any[];
draw: number;
recordsFiltered: number;
recordsTotal: number;
}
#Component({
selector: 'app-manage-templates',
templateUrl: './manage-templates.component.html',
styleUrls: ['./manage-templates.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ManageTemplatesComponent implements AfterViewInit, OnDestroy, OnInit {
// Creating formgroup object
createEmailTemplate = new FormGroup({
templateName: new FormControl('', [Validators.required]),
templateBody: new FormControl('', [Validators.required]),
templateDesc: new FormControl('', [Validators.required])
});
// Initializing variables
submitted = false;
editFlag = false;
#ViewChild(DataTableDirective)
dtElement: DataTableDirective;
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<Template> = new Subject();
templates: Template[];
constructor(
private http: HttpClient,
private formBuilder: FormBuilder,
private postData: emailTemplatesService,
private notifier: NotifierService,
private router: Router
) { }
ngOnInit(): void {
const that = this;
this.dtOptions = {
searching: false,
pagingType: 'full_numbers',
pageLength: 10,
serverSide: true,
processing: true,
ajax: (dataTablesParameters: any, callback) => {
that.http
.post<DataTablesResponse>(
Globals.baseAPIUrl + '/getEmailTemplates',
JSON.stringify({ dataTablesParameters })
).subscribe(resp => {
that.templates = resp.data;
callback({
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: []
});
});
},
columns: [
{ title: 'Template Name', data: 'template_name' },
{ title: 'Template Desc', data: 'template_desc' },
{ title: 'Status', data: 'template_status' },
]
};
}
ngAfterViewInit(): void {
this.dtTrigger.next();
}
ngOnDestroy(): void {
// Do not forget to unsubscribe the event
this.dtTrigger.unsubscribe();
}
rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
// Destroy the table first
dtInstance.destroy();
// Call the dtTrigger to rerender again
this.dtTrigger.next();
});
}
get formfields() { return this.createEmailTemplate.controls; }
// On form submit
onSubmit() {
this.submitted = true;
if (this.createEmailTemplate.invalid) {
return;
}
this.postData.createTemplate(JSON.stringify(this.createEmailTemplate.value)).subscribe(
data => {
this.notifier.notify(data['status'], data['message']);
if (data['status'] === 'success') {
this.rerender();
}
}
);
}
// On edit button
editTemplate(template_id) {
this.postData.getTemplateDetails(template_id).subscribe(
data => {
this.createEmailTemplate.patchValue({
templateName: data['message']['0']['templateName'],
templateDesc: data['message']['0']['templateDesc'],
templateBody: data['message']['0']['templateBody']
});
this.editFlag = true;
}
);
}
loadTemplates() {
this.editFlag = false;
this.rerender();
}
}
manage-templates.component.html
<div class="animated fadeIn">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<strong>Create Email Template</strong>
</div>
<form [formGroup]="createEmailTemplate" (ngSubmit)="onSubmit()" action="" method="post" class="form-horizontal">
<div class="card-body">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="select1">Template Name</label>
<div class="col-md-6">
<input type="text" formControlName="templateName" class="form-control" placeholder="Template Name"
[ngClass]="{ 'is-invalid': submitted && formfields.templateName.errors }">
<span class="invalid-feedback" *ngIf="formfields.templateName.errors">Please Enter
Template Name</span>
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="select1">Template Description</label>
<div class="col-md-6">
<input type="text" formControlName="templateDesc" class="form-control" placeholder="Template Description"
[ngClass]="{ 'is-invalid': submitted && formfields.templateDesc.errors }">
<span class="invalid-feedback" *ngIf="formfields.templateDesc.errors">Please Enter
Template Description</span>
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="text-input">Email Body</label>
<div class="col-md-6">
<editor [(ngModel)]="dataModel" class="form-control" formControlName="templateBody"
[ngClass]="{ 'is-invalid': submitted && formfields.templateBody.errors }"></editor>
<span class="invalid-feedback" *ngIf="formfields.templateBody.errors">Email body need
not be empty</span>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" *ngIf="editFlag == false" class="btn btn-sm btn-primary" type="submit"><i class="fa fa-dot-circle-o"></i> Submit</button>
<button type="submit" *ngIf="editFlag == true" class="btn btn-sm btn-primary" type="submit"><i class="fa fa-dot-circle-o"></i> Update</button>
<button type="reset" class="btn btn-sm btn-danger" *ngIf="editFlag == false"><i class="fa fa-ban"></i> Reset</button>
<button type="reset" class="btn btn-sm btn-danger" *ngIf="editFlag == true" (click)="loadTemplates()"><i class="fa fa-ban"></i> Cancel</button>
</div>
</form>
</div>
</div>
</div>
<!--/.row-->
<div class="row" *ngIf="editFlag == false">
<div class="col-lg-12">
<div class="card">
<div class="card-header">
<i class="fa fa-align-justify"></i> Email Templates
</div>
<div class="card-body template_list">
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover" width="100%">
<thead>
<tr>
<th>Template Name</th>
<th>Template Desc</th>
<th>Template Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody *ngIf="templates?.length != 0">
<tr *ngFor="let template of templates">
<td>{{ template.template_name }}</td>
<td>{{ template.template_desc }}</td>
<!-- <td>{{ template.template_status }}</td> -->
<td>
<span *ngIf="template.template_status == true" class="badge badge-success"> Active </span>
<span *ngIf="template.template_status == false" class="badge badge-danger">Inactive</span>
</td>
<td>
<a routerLink="edit" (click)="editTemplate(template.template_id)">Edit</a>
/
<a routerLink="disable/{{template.template_id}}" *ngIf="template.template_status == true">Deactivate</a>
<a routerLink="enable/{{template.template_id}}" *ngIf="template.template_status == false">Activate</a>
</td>
</tr>
</tbody>
<tbody *ngIf="templates?.length == 0">
<tr>
<td colspan="3" class="no-data-available">No data!</td>
</tr>
<tbody>
</table>
</div>
</div>
</div>
</div>
</div>
on editing an email template datatable hides and the values displayed in the form. Here i haven't write code for update form values. I want to repopulate the page on pressing "Cancel" button. On cancel button content in the datatable repopulates without pagination or any styles of datatable.
ERROR TypeError: "this.dtElement is undefined"
Here is my solution, the order of ViewChild/dtElement/... is important in this case
export class DemoComponent implements OnInit {
#ViewChild(DataTableDirective)
dtElement: DataTableDirective;
dtOptions: any = {};
dtInstance: DataTables.Api;
dtTrigger: Subject<any> = new Subject();
dt_data: any = {};
......
ngOnInit() {
this.dtOptions = {
...
};
}
ngAfterViewInit(){
//Define datatable
this.dtTrigger.next();
}
ngOnDestroy(): void {
this.dtTrigger.unsubscribe();
}
SomeFunction(){
//return the updated record, all the update function must be using rerender
this.dt_data = resp;
this.rerender();
}
rerender(): void {
try {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
// Destroy the table first
dtInstance.destroy();
// Call the dtTrigger to rerender again
this.dtTrigger.next();
});
} catch (err) {
console.log(err);
}
}
When I faced this same issue, I managed to solve it by using [hidden] instead of *ngIf. Aparently, ViewChild couldn't find the DataTableDirective because it wasn't in the HTML (thanks to *ngIf) resulting in the error, since this.dtElement was equal to undefined.
I suggest you try using this:
<div class="row" [hidden]="editFlag == true">
<!-- DataTable Content -->
</div
If you are using Forms and every time you submit new data and data coming from post request is different you can use something like this (angular 8) -
export class Demo implements OnDestroy, OnInit, AfterViewInit {
//this part did the job for me #view...
#ViewChild(DataTableDirective, { static: false }) datatableElement: DataTableDirective;
dtElement: DataTableDirective;
dtOptions: any = {};
dtInstance: DataTables.Api;
dtTrigger: Subject<any> = new Subject();
dt_data: any = {};
......
ngOnInit() {
this.dtOptions = {
paging: false,
"ordering": false,
dom: 'Bfrtip',
buttons: [
'copy',
'csv',
'excel'
]
};
}
ngAfterViewInit(){
this.dtTrigger.next();
}
ngOnDestroy(): void {
this.dtTrigger.unsubscribe();
}
getData(){
//post request and when assigning data to variable
this.dt_data = resp;
this.rerender();
}
rerender(): void {
//this.datatableElement is important
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.destroy();
this.dtTrigger.next();
});
}
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
};
}
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