Not able to use ng-model - angular2-directives

Not able to use ng-model. I am getting this error even after importing
formsmodule in app.module.ts Below is my both the file component and module. Please correct me where I am wrong. Thanks In Advance
Promise rejection: Template parse errors:
Can't bind to 'ng-model' since it isn't a known property of 'input'. ("
<div>
<label>name: </label>
<input type="text" [ERROR ->][(ng-model)]="hero.name" placeholder="name">
</div>
"): ng:///AppModule/AppComponent.html#5:28 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:`enter code here`
Can't bind to 'ng-model' since it isn't a known property of 'input'. ("
<div>
<label>name: </label>
<input type="text" [ERROR ->][(ng-model)]="hero.name" placeholder="name">
</div>
"): ng:///AppModule/AppComponent.html#5:28
at syntaxError (http://localhost:3000/node_modules/#angular/compiler/bundles/compiler.umd.js:1513:34) [<root>]
at TemplateParser.parse (http://localhost:3000/node_modules/#angular/compiler/bundles/compiler.umd.js:11522:19) [<root>]
at JitCompiler._compileTemplate (http://localhost:3000/node_modules/#angular/compiler/bundles/compiler.umd.js:25296:39) [<root>]
at eval (http://localhost:3000/node_modules/#angular/compiler/bundles/compiler.umd.js:25220:62) [<root>]
at Set.forEach (native) [<root>]
at JitCompiler._compileComponents (http://localhost:3000/node_modules/#angular/compiler/bundles/compiler.umd.js:25220:19) [<root>]
at createResult (http://localhost:3000/node_modules/#angular/compiler/bundles/compiler.umd.js:25105:19) [<root>]
at Zone.run (http://localhost:3000/node_modules/zone.js/dist/zone.js:125:43) [<root> => <root>]
at http://localhost:3000/node_modules/zone.js/dist/zone.js:760:57 [<root>]
at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:165:47) [<root> => <root>]
at drainMicroTaskQueue (http://localhost:3000/node_modules/zone.js/dist/zone.js:593:35) [<root>]
at XMLHttpRequest.ZoneTask.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:464:25) [<root>] Error: Template parse errors:
This is my app.module.ts:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
This is my app.component.ts:
import { Component } from '#angular/core';
export class Hero{
id: number;
name: string;
}
#Component({
selector: 'my-app',
template: `<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input type="text" [(ng-model)]="hero.name" placeholder="name">
</div>
`
})
export class AppComponent {
title = 'Angular';
hero :Hero = {
id: 1,
name: 'windstorm'
};
}

It's ngModel, not ng-model.
So it should be:
<input type="text" [(ngModel)]="hero.name" placeholder="name">
See Template Syntax.

Related

How to pass vuelidate object with props for jest test?

I have several components inside each of them have fields that are validated with vuelidate. All field validation rules are described in the parent component wrapper in the child components, I pass the object :v="$v", everything works. But in the test, when mounting, I get an error, and as I understand it, because when mounting, I do not pass this object, tell me how to do it right?
parent wrapper
<template>
<VModal>
<template v-slot:content>
<div class="layer">
<institutes-info
:v="$v"
ref="info-component"
/>
</div>
</template>
</VModal>
</template>
export default {
name: "WrapModalInstitutes",
validations: {
si: {
name: {
required,
maxLength: maxLength(256),
},
},
},
}
child component
<template>
<form action="" id="form-info" #submit.prevent="uploadInfo($event, si.id)">
<p class="sub-text">{{ $t("vnz.info") }}</p>
<div class="institut-info">
<div class="input-group" :class="{ 'form-group--error': v.si.name.$error, 'form-group--success': !v.si.name.$invalid }">
<label for="name-institut">{{ $t("vnz.nameVNZ") }}</label>
<div class="input-container">
<input id="name-institut" name="title" type="text" :placeholder="$t('vnz.nameVNZ')" v-model.trim="name" #keydown="trimSpecialCharacters($event)" #input="trimSpecialCharacters($event, 'name')">
<div class="error" v-if="!v.si.name.required && v.si.name.$dirty">{{ $t("vnz.notEmpty") }}</div>
</div>
</div>
</div>
<button v-if="edit" type="submit" class="btn-primary edit" :disabled="submitStatus === 'PENDING'">{{ $t("vnz.save") }}</button>
</form>
</template>
export default {
name: "InstitutesInfoModal",
props: ['v'],
}
test file
import Vuex from "vuex"
import {mount, createLocalVue, config} from "#vue/test-utils"
import InstitutesInfo from '../../assets/src/components/InstitutesInfo'
import Vuelidate from 'vuelidate'
import VueTheMask from 'vue-the-mask'
import translations from "../../assets/src/common-resources/translations/translations"
import fetchMock from 'jest-fetch-mock'
const locale = "uk";
config.mocks["$t"] = msg => translations[locale][msg]
fetchMock.enableMocks()
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(Vuelidate)
localVue.use(VueTheMask)
describe('testing institute-info component', () => {
let store;
let mutations;
let actions;
beforeEach(() => {
mutations = {
'institutes/EDIT_SI_OBJ': jest.fn(),
'institutes/SUBMIT_STATUS': jest.fn()
}
actions = {
'institutes/UPLOAD_INFO': jest.fn()
}
store = new Vuex.Store({
modules: {
institutes: {
state: {
si: {
name: null,
},
submitStatus: null
},
mutations,
actions
}
}
})
})
test('some test"',() => {
const wrapper = mount(InstitutesInfo, {
store, localVue
})
})
})
[Vue warn]: Error in render: "TypeError: Cannot read property 'si' of undefined"

The page is showing some error with Reactve components

<input type="text" name="" id=""
class="form-control" [formControl]='fname'
placeholder="Enter your name">
and this is the error i am getting
ERROR in src/app/myform/myform.component.html:12:54 - error TS2339: Property 'fname' does not exist on type 'MyformComponent'.
12 class="form-control" [formControl]='fname'
~~~~~
src/app/myform/myform.component.ts:9:16
9 templateUrl: './myform.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component MyformComponent.
try this:
Typescript
import { Component } from '#angular/core';
import { FormGroup,FormControl } from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
form = new FormGroup({
fname : new FormControl(''),
});
onsubmit(){
//submit button
}
}
HTML
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<label>
Name:
<input type="text" formControlName="fname" placeholder="Enter your fname">
</label>
</form>
app.module.ts //module
import { FormsModule,ReactiveFormsModule } from '#angular/forms';
On your typescript you need to add the following function to get the value from your form:
get fname(){
return this.formName.get('fname')
}

nuxtjs nuxt-validate not works

I have installed with npm
npm i --save nuxt-validate
a component for the validation of a form. But not works. Below the plugins/validate.js:
import { extend } from "vee-validate";
extend("my-validation", { message: "This {_field_} is invalid.", validate: value => {
// ...
return true; } });
In my nuxt.config.js:
{src: '~plugins/validate.js', ssr: true}
And in my page.vue in the script I have this situation:
import { ValidationProvider } from 'vee-validate';
export default {
components: {
ValidationProvider
},
and in my template this content:
<ValidationProvider rules="my-validation" v-slot="{ errors }" name="nameRegister">
<input type="text" name="nameRegister" id="nameRegister" tabindex="1" class="form-control"
placeholder="Name" value="" v-model="nameRegister">
</ValidationProvider>
During the field writing, nothing happened, why?
thanks

Angular 8 - Form Group Values are always empty

Am new to angular and am starting off with a simple login form. However the form values are always showing up as empty - even if values have been entered before form submission.
I have created a login component which is imported in app module. The page comes up, but the submission does not carry any values. I have removed all Angular validation checks for debugging but the values received in my onsubmit function are still empty.
I have pasted the component code.Below.
login.component.html
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div class="form-group" >
<div class="form-group">
<input type="email" class="form-control" formcontrolname="username"
placeholder="Email Id" required autofocus/><br/>
</div>
<div class="form-group">
<input type="password" class="form-control" formcontrolname="password" placeholder="Password" required/><br/>
</div>
<div class="form-group">
<button>Login</button>
<a href="/public/register" class="btn" >Register</a>
</div>
app.component
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
#NgModule({
imports: [ BrowserModule, AppRoutingModule, FormsModule,
ReactiveFormsModule ],
declarations: [ AppComponent, HelloComponent, LoginComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
login.component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
submitted = false;
returnUrl = '';
constructor(
private formBuilder: FormBuilder,
private router: Router
) {
}
ngOnInit() {
this.loginForm = this.formBuilder.group ({
username: ['', Validators.required],
password: ['', Validators.required]
});
}
get user() { return this.loginForm.controls; }
onSubmit() {
// stop if form is invalid
/* if (this.loginForm.invalid) {
console.log("Returning");
return;
} */
this.submitted = true;
console.log('login values:');
console.log(this.user.username.value, this.user.password.value);
this.returnUrl='/home';
// this.router.navigate([this.returnUrl]);
}
}
You can try this:
get user() { return this.loginForm.value; }
Knew it would be something super silly and trivial - turned out to be a case sensitivity problem issue on my end. Changed 'formcontrolname' to 'formControlName' and it started working! Duh!

ReactiveForms with custom input

I'm getting the following error when trying to create a form using a custom component.
Error: No value accessor for form control with name:
'nomeEmpresaAerea'
Error: No value accessor for form control with name: 'nomeEmpresaAerea'
Stack trace:
_throwError#webpack-internal:///./node_modules/#angular/forms/esm5/forms.js:2510:11
setUpControl#webpack-internal:///./node_modules/#angular/forms/esm5/forms.js:2380:9
FormGroupDirective.prototype.addControl#webpack-internal:///./node_modules/#angular/forms/esm5/forms.js:6736:9
FormControlName.prototype._setUpControl#webpack-internal:///./node_modules/#angular/forms/esm5/forms.js:7386:45
FormControlName.prototype.ngOnChanges#webpack-internal:///./node_modules/#angular/forms/esm5/forms.js:7299:13
checkAndUpdateDirectiveInline#webpack-internal:///./node_modules/#angular/core/esm5/core.js:12581:9
checkAndUpdateNodeInline#webpack-internal:///./node_modules/#angular/core/esm5/core.js:14109:20
checkAndUpdateNode#webpack-internal:///./node_modules/#angular/core/esm5/core.js:14052:16
debugCheckAndUpdateNode#webpack-internal:///./node_modules/#angular/core/esm5/core.js:14945:55
debugCheckDirectivesFn#webpack-internal:///./node_modules/#angular/core/esm5/core.js:14886:13
View_EmpresaCadastroComponent_0/<#ng:///EmpresaModule/EmpresaCadastroComponent.ngfactory.js:80:5
debugUpdateDirectives#webpack-internal:///./node_modules/#angular/core/esm5/core.js:14871:12
checkAndUpdateView#webpack-internal:///./node_modules/#angular/core/esm5/core.js:14018:5
callViewAction#webpack-internal:///./node_modules/#angular/core/esm5/core.js:14369:21
this is my reactive form:
import { Component, OnInit, Input } from '#angular/core';
import { Router } from '#angular/router';
import { HttpClient } from '#angular/common/http';
import { FormArray, FormBuilder, FormGroup, Validators } from '#angular/forms';
#Component({
selector: 'app-empresa-cadastro',
templateUrl: './empresa-cadastro.component.html',
styleUrls: ['./empresa-cadastro.component.css']
})
export class EmpresaCadastroComponent implements OnInit {
#Input() empresa = {};
empresaForm: FormGroup;
constructor(private route: Router, private http: HttpClient, private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.empresaForm = this.fb.group({
nomeEmpresaAerea: '',
status: 'S',
});
}
this is my html:
<form [formGroup]="empresaForm" (ngSubmit)="onSubmit()">
<div style="margin-bottom: 1em">
<button type="submit" [disabled]="empresaForm.pristine" class="btn btn-success">Cadastrar</button>
<button type="button" (click)="limpar()" [disabled]="empresaForm.pristine" class="btn btn-danger">Limpar</button>
</div>
<div class="form-group">
<label class="center-block">Nome:
<input class="form-control" >
<app-pf-input-text formControlName="nomeEmpresaAerea" ></app-pf-input-text>
</label>
</div>
</form>
pf-input-text.componente.ts:
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-pf-input-text',
templateUrl: './pf-input-text.component.html',
styleUrls: ['./pf-input-text.component.scss']
})
export class PfInputTextComponent implements OnInit {
#Input() id: string;
#Input() name: string;
#Input() value: string;
#Input() placeholder: string;
//falta trim
#Input() maxlength: string;
#Input() minlength: string;
#Input() disabled: boolean;
#Input() required: boolean;
constructor() { }
ngOnInit() {
}
}
pf-input-text.component.html
<div class="input-group">
<input
type="text"
id="{{id}}"
name="{{name}}"
placeholder="{{placeholder}}"
attr.maxlength="{{maxlength}}"
class="form-control"
disabled="{{disabled}}"
required="{{required}}">
</div>
try this in reactive form component
this.empresaForm = new FormGroup({
'nomeEmpresaAerea': new FormControl(null, Validators.required)});