Complex object dynamic form creation with Angular Reactive Forms - arrays

I have a products object as mentioned below from which I have to create a complex form
component.ts
import { Component, OnInit } from "#angular/core";
import { FormBuilder, FormGroup, FormArray, Validators } from "#angular/forms";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
products = [
{
Id: 1,
Name: "productA",
referralCode: "codeA",
webUrl: "https://productA.com",
allowReferralCode: true
},
{
Id: 2,
Name: "productb",
referralCode: null,
webUrl: "https://productb.com",
allowReferralCode: true
},
{
Id: 3,
Name: "productC",
referralCode: null,
webUrl: "https://productC.com",
allowReferralCode: false
}
];
productForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.productForm = this.fb.group({
products: new FormArray([])
});
this.products.forEach(item => {
if (item.referralCode !== null && item.allowReferralCode) {
this.t.push(
this.fb.group({
productId: [""],
referralCode: [""],
link: [""]
})
);
} else if (item.allowReferralCode) {
this.t.push(
this.fb.group({
productId: [""],
referralCode: [""]
})
);
} else if (!item.allowReferralCode) {
this.t.push(
this.fb.group({
productId: [""],
link: [""]
})
);
}
});
}
get f() {
return this.productForm.controls;
}
get t() {
return this.f.products as FormArray;
}
get productsFormGroups() {
return this.t.controls as FormGroup[];
}
onSubmit(form) {
alert(
"SUCCESS!! :-)\n\n" + JSON.stringify(this.productForm.value, null, 4)
);
}
}
Below is the HTML:
component.html
<form [formGroup]="productForm" (submit)="onSubmit(productForm)">
<div *ngFor="let product of products">
<div
*ngIf="product.referralCode !== null && product.allowReferralCode; else showWithReferalCode"
>
<div class="card ml-3 mt-3 mb-3" style="width: 18rem;">
<h4 class="mb-0 ml-3">{{product.Name | titlecase}}</h4>
<div class="card-body">
<div class="new-custom-radio ml-2 mb-3">
<div class="custom-control custom-radio">
<input
type="radio"
id="customRadio1"
name="customRadio"
class="custom-control-input"
/>
<label class="custom-control-label" for="customRadio1"
>I have a Referral Code</label
>
</div>
<div class="referral-code-input">
<input type="text" class="form-control form-control-lg" />
</div>
</div>
<div class="new-custom-radio ml-2 mb-3">
<div class="custom-control custom-radio">
<input
type="radio"
id="customRadio2"
name="customRadio"
class="custom-control-input"
/>
<label class="custom-control-label" for="customRadio2"
>I have a Custom Web Link</label
>
</div>
<div class="referral-code-input">
<input type="text" class="form-control form-control-lg" />
</div>
</div>
</div>
</div>
</div>
<ng-template #showWithReferalCode>
<div *ngIf="product.allowReferralCode; else showWebUrl">
<div class="card ml-3 mt-3 mb-3" style="width: 18rem;">
<h4 class="mb-0 ml-3">{{product.Name | titlecase}}</h4>
<div class="m-3 form-group">
<label for="exampleInputEmail1">I have Referral code</label>
<input
type="text"
class="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"
/>
</div>
</div>
</div>
<ng-template #showWebUrl>
<div class="card ml-3 mt-3 mb-3" style="width: 18rem;">
<h4 class="mb-0 ml-3">{{product.Name | titlecase}}</h4>
<div class="m-3 form-group">
<label for="exampleInputEmail1">I have WebUrl</label>
<input
type="text"
class="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"
/>
</div>
</div>
</ng-template>
</ng-template>
</div>
<div class="mt-2 mb-4 text-center">
<button class="btn btn-primary">Save</button>
</div>
</form>
I want to create a dynamic form for some conditions as shown in the screenshot below.
Now let me break it down whenever I have a referral code and allowReferralCode=true within my product I need to allow users to choose either referral code or custom code. At the same time if any product doesn't have a referral code and allowReferralCode=true then they will have to ask for a referral code and also if allowReferralCode=false then enter a direct URL.
I'm trying to build a dynamic form with form builder and FormArrays and it seems like as I have conditions in my HTML I'm unable to set form controls of the FormArray to form.
Below is the stack blitz version of the same.
stackblitz code
Whenever I'm trying to form control name to the inputs I'm getting this kind of error
**ERROR Error: Cannot find control with name: 'referralCode'**
Any help would be greatly appreciated.
Thanks in advance.

Related

setup returns empty sections before getSectionAndSubsection load data

I am a writing an application using vue 3. I want to load data from a server using axios
The setup is return empty section array but course.getSectionAndSubsection gets data from the server
Template
The template displays the data get from server
<div v-if="state.length > 0 ">
<div class="__course-sub-section" v-for="(section, index) in state.section" :key="index">
<div><input type="text" placeholder="Enter Section Title" v-model="section.section_title" class="section-title form-control x_focus"></div>
<div class="__upload-section d-flex justify-content-between align-items-center" v-for="(sub_section, idx) in section.sub_state" :key="idx">
<div class="d-flex">
<input type="text" placeholder="Enter Sub Section Title" v-model="sub_section.sub_section_title" class="section-title form-control x_focus">
<div class="__choose">
<label for="">
<div>
<input type="file" #change="uploadFile( $event, index, idx )" name="" id="">
Upload File
</div>
<img src="#/assets/images/upload.png" alt="">
</label>
</div>
</div>
<div class="__sub-section-image">
<div class="placeholders">
<div v-if="sub_section.subSectionAdded">
<img :src="sub_section.imageURL" alt="">
</div>
<div v-if="!sub_section.subSectionAdded">
<img src="#/assets/images/upload.png" alt="">
</div>
</div>
</div>
<button #click="addSubSection(index)" class="app_button primary_btn d-flex mt-4">
Add Sub Section
</button>
</div>
</div>
</div>
</div>
Javascript
I tried getting the data from the server. but the setup return empty section array before getting the data from the server.
<script>
export default {
name: 'EditSubSection',
setup(){
let state = reactive({"sections" :[
{
'section_title': '',
'sub_state': [
{
'sub_section_title': '',
'imageURL': '' as any,
'url': '',
'subSectionAdded': false
}
]
}
]});
Course.getSectionAndSubsections("get-section-and-subsections", id)
.then(response => {
state.sections = response.data.sections;
console.log("state form edit sub state",state.sections);
})
.catch(err => {})
.finally(() => {
showLoader(false)
});
return {state}
}
}
</script>

How to set value of an input from Redux store, but then still be able to write in that input and update value?

My input is also like a searchbox: I want to be able to search for names on the input but then I want to be able to click a name from the dropdown search results and set the input with that value. I then want to be able to search again if I want to change that value.
Tried using DefaultValue and uncontrolled components, but neither worked. Not sure if I used them right though.
class PublishTest extends Component {
constructor() {
super();
this.state = {
showRows: false,
numberOfRows: ["row"],
search: "",
searchResults: [],
insightListActive: false,
insightTagsActive: false
};
this.hideOrShowRows = this.hideOrShowRows.bind(this);
this.addNewRow = this.addNewRow.bind(this);
this.searchAllUsers = this.searchAllUsers.bind(this);
this.onChangeInsight = this.onChangeInsight.bind(this);
this.clearInput = this.clearInput.bind(this);
this.clearInsightList = this.clearInsightList.bind(this);
this.searchInsightTags = this.searchInsightTags.bind(this);
this.clearTagList = this.clearTagList.bind(this);
}
componentDidMount() {
this.props.getLoginCredential();
this.props.getAllRoles();
}
hideOrShowRows() {
this.setState({
showRows: !this.state.showRows
});
}
addNewRow() {
this.setState({
numberOfRows: [...this.state.numberOfRows, "row"]
});
}
searchAllUsers(e) {
this.setState({
search: e.target.value
});
const searchOption = this.state.search;
fetch("http://localhost:3500/soiapi/", {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
data: [
{
name: "searchUser",
urlparameter: { search: searchOption, appId: "1" },
parameter: ""
}
]
})
})
.then(res => res.json())
.then(data => {
this.setState({
searchResults: data[0]
});
});
}
onChangeInsight = e => {
this.props.insightOnChangeValue(e.target.value);
this.props.searchInsights(e.target.value);
this.setState({
insightListActive: true
});
};
clearInput() {
this.setState({
search: "",
searchResults: []
});
}
clearInsightList() {
this.setState({
insightListActive: false
});
}
searchInsightTags(e) {
this.props.getInsightTags(e.target.value);
this.setState({
insightTagsActive: true
});
}
clearTagList() {
this.setState({
insightTagsActive: false
});
}
render() {
const { searchResults } = this.state;
let rows;
let button;
let icon;
if (this.state.showRows) {
rows = this.state.numberOfRows.map((row, i) => (
<div>
<Row index={i} />
</div>
));
button = (
<button
onClick={this.addNewRow}
className="Button--secondary float-right"
>
Add Row
</button>
);
icon = (
<i aria-hidden="true" className="Icon Icon--minus-small iconFont"></i>
);
} else if (!this.state.showRows) {
icon = (
<i aria-hidden="true" className="Icon Icon--plus-small iconFont"></i>
);
}
if (this.props.user.userDTO) {
const { userDTO } = this.props.user;
const insightSearchResults = this.props.insightReducerValue
.insightList[0];
return (
<div style={{ padding: "5px" }} className="publish-container">
<h4 className="publish-h4">Publish Insights</h4>
<h6 className="publish-h6">Insight Details</h6>
<hr className="line-style" />
<section id="publish-section-1">
<div class="Grid">
<div class="Col Col--3">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label insight-label">
Insight Name <span className="asterisk">*</span>:
</label>
<div id="insight-container">
<input
type="text"
placeholder="Insight Name"
onChange={this.onChangeInsight}
onFocus={this.clearInsightList}
onBlur={this.clearInsightList}
className="Form-input"
value={this.props.insightReducerValue.insightValue}
/>
{this.state.insightListActive ? (
<InsightList insights={insightSearchResults} />
) : null}
</div>
</div>
</div>
</div>
<div class="Col Col--3">
<div class="grid-block">
<div class="Form-group publish-insights-input">
<label class="Form-label">
Insight Source <span className="asterisk">*</span>:
</label>
<select
id="insight-source"
role="combobox"
class="Form-input"
>
<option
disabled="disabled"
selected="selected"
aria-disabled="true"
>
Choose one
</option>
<option>Tableau</option>
<option>Qlik</option>
<option>D3JS</option>
<option>CXI</option>
</select>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-2">
<div class="Grid">
<div class="Col Col--6">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label class="Form-label">
URL <span className="asterisk">*</span>:
</label>
<input type="text" placeholder="URL" class="Form-input" />
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-3">
<div class="Grid">
<div class="Col Col--6">
<div class="grid-block">
<div className="publish-insights-input">
<label class="Form-label">
Description <span className="asterisk">*</span>:
</label>
<textarea
placeholder="Description"
class="Form-input"
></textarea>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-4">
<div class="Grid">
<div class="Col Col--3">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label third-div-p">
POC Name <span className="asterisk">*</span>:
</label>
<input
type="text"
placeholder="Name"
className="Form-input"
value={`${userDTO.firstName} ${userDTO.lastName}`}
/>
</div>
</div>
</div>
<div class="Col Col--3">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label third-div-p">
Group Distro (E-mail Address)
<span className="asterisk">*</span>:
</label>
<input
type="text"
placeholder="Email"
class="Form-input"
value={userDTO.emailAddress}
/>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-5">
<div class="Grid">
<div class="Col Col--6">
<div class="grid-block">
<div class="Form-group publish-insights-input">
<div class="Form-checkbox is-restricted">
<input
id="restricted"
name="checkboxDefault"
type="checkbox"
/>
<label for="restricted">Is Restricted</label>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-6">
<div class="Grid">
<div class="Col Col--2">
<div class="grid-block">
<div id="tree-section">
<label id="category-label" className="Form-label">
Category <span className="asterisk">*</span>
</label>
<div id="tree-container">
<PublishInsightsTree />
</div>
</div>
</div>
</div>
<div class="Col Col--4">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label third-div-p">
Add Insight Tags <span className="asterisk">*</span>:
</label>
<input
type="text"
onChange={e => this.searchInsightTags(e)}
onFocus={this.clearTagList}
onBlur={this.clearTagList}
placeholder="Write some insight tags"
className="Form-input"
/>
</div>
{
this.state.insightTagsActive ?
<div>
{
this.props.insightTags ?
<InsightTags tags={this.props.insightTags[0]} />
: null
}
</div>
: null
}
</div>
<div class="grid-block">
<div class="Grid">
<div class="Col Col--7 img-url-input">
<div class="grid-block">
<div
id="file-div"
class="Form-group publish-insights-input"
>
<label class="Form-label">
Image URL <span className="asterisk">*</span>:
</label>
<input
type="text"
placeholder="Insight Name"
class="Form-input"
/>
</div>
</div>
</div>
<div class="Col Col--5">
<div class="grid-block">
<button class="Button--secondary upload-image-button">
Upload Image
</button>
</div>
</div>
<div class="Col Col--7 url-description">
<div class="grid-block">
<p>
Please copy paste the generated URL after uploading
image file.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-7">
<h6 className="publish-h6">Role Details</h6>
<hr className="line-style" />
</section>
<section id="publish-section-8">
<div class="Grid">
<div class="Col Col--2">
<div class="grid-block">
<label id="roles-label" className="Form-label">
Assign to Role <span className="asterisk">*</span>
</label>
<div id="all-roles">
{this.props.listOfRoles ? (
<ListOfRoles roles={this.props.listOfRoles} />
) : null}
</div>
</div>
</div>
<div class="Col Col--4">
<div class="grid-block assign-user-div">
<label className="Form-label label-spacing">
Assign to Individual User:
</label>
<div className="Form-group">
<textarea
onChange={this.searchAllUsers}
type="text"
placeholder="Look up by EID/Name"
onFocus={this.clearInput}
onBlur={this.clearInput}
className="Form-input assign-user-textarea"
value={this.state.search}
></textarea>
{searchResults.length > 0 ? (
<div id="user-list">
{searchResults ? (
<UserList searchResults={this.state.searchResults} />
) : null}
</div>
) : null}
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-9">
<h6 className="publish-h6 metadata-heading" onClick={this.hideOrShowRows}>
<span id="metadata-icon">{icon}</span>
Metadata Info
</h6>
<hr className="line-style color" />
</section>
<section id="publish-section-10">
<div class="Grid">
<div class="Col Col--12 add-row-col">
<div class="grid-block">{button}</div>
</div>
</div>
{rows}
</section>
</div>
);
} else {
return null;
}
}
}
const mapStateToProps = state => ({
user: state.LoginReducer.loginInfo,
searchUser: state.LoginReducer.searchUser,
insightReducerValue: state.SideDrawerReducer,
listOfRoles: state.LoginReducer.listOfRoles,
insightTags: state.SideDrawerReducer.insightTags
});
export default connect(
mapStateToProps,
{
getLoginCredential,
searchUser,
insightOnChangeValue,
searchInsights,
getAllRoles,
getInsightTags
}
)(PublishTest);
This is the part of the code I need help with:
<input
type="text"
placeholder="Insight Name"
onChange={this.onChangeInsight}
onFocus={this.clearInsightList}
onBlur={this.clearInsightList}
className="Form-input"
value={this.props.insightReducerValue.insightValue}
/>
{this.state.insightListActive ? (
<InsightList insights={insightSearchResults} />
) : null}
Since your code is a little messy, I made a sandbox that fetches some data from a dummy API, stores that data to our local component state. We have a text field where we can type in usernames and a list of matching usernames will appear as a dummy drop, clicking any one of those usernames will set the value in the text field. It's pretty straight forward will give you an idea on how to get started.
EDIT:
Sandbox Link: https://codesandbox.io/s/eloquent-pascal-pf3hd?fontsize=14
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
input: "",
users: [],
dropdown: []
};
async componentDidMount() {
let users = await fetch("https://jsonplaceholder.typicode.com/users");
users = await users.json();
this.setState({ users });
}
handleChange = e => {
this.setState({ input: e.target.value }, () => {
let results = this.state.users.filter(user => {
return user.username.indexOf(this.state.input) > -1;
});
this.setState({ dropdown: results });
});
};
handleSelect = username => e => {
this.setState({ input: username }, () => this.setState({ dropdown: [] }));
};
render() {
return (
<div className="App">
<h1>Search</h1>
<input
type="text"
name="input"
onChange={this.handleChange}
value={this.state.input}
/>
{this.state.dropdown.map(d => (
<h3 onClick={this.handleSelect(d.username)} key={d.id}>
{d.username}
</h3>
))}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Could you start off by loading all possible search results into state or props (e.g. under this.props.searchResults)? Then you could try using the datalist tag. Not quite sure if this was what you were going for, but it looked like something like that could work for you.
<input type="text"
defaultValue={this.props.insightReducerValue.insightValue}
list="inputOptions"
onChange={(e) => console.log("Current input field value: ", e.target.value)} />
<datalist id="inputOptions">
{this.props.searchResults.map((item, key) =>
<option key={key} value={item} />
)}
</datalist>
P.S. Check the supported browsers list under the link.

angular-cli form validations

This is the output of my code that i excuted with below codes
My problem is that i am unable do validations here.. after clicking the AddEmployee button even without any data in it.. it is getting added to the data
below is the code of app.component.html
<div class = "container">
<h1>{{title}}</h1>
<h2>Add Employee:</h2>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name"
[(ngModel)]="model.name" placeholder="Enter Your Name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="position">Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="position" name="position" [(ngModel)]="model.position" placeholder="Enter your position">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="salary">Salary:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="salary" name="salary" [(ngModel)]="model.salary" placeholder="Enter Salary">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" (click)="addEmployee()">Add Employee</button>
</div>
</div>
</form>
<h2>Employee Details</h2>
<table class="table table-bordered">
<thead>
<tr>
<th width=400>Name</th>
<th width=400>Position</th>
<th width=200>Salary</th>
<th width=400>Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees; let i=index">
<td>{{employee.name}}</td>
<td>{{employee.position}}</td>
<td>{{employee.salary}}</td>
<td>
<a class="btn btn-success" (click)="editEmployee(i)">Edit</a>
<a class="btn btn-danger" (click)="deleteEmployee(i)">Delete</a>
</td>
</tr>
</tbody>
</table>
<h2>Update Employee:</h2>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name"
name="name" [(ngModel)]="model2.name" placeholder="Enter Your Name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="position">Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="position" name="position" [(ngModel)]="model2.position" placeholder="Enter your position">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="salary">Salary:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="salary" name="salary" [(ngModel)]="model2.salary" placeholder="Enter Salary">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" (click)="updateEmployee()">update Employee</button>
</div>
</div>
</form>
</div>
this is the code of app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Employee Details';
employees = [{
name: "Sunil",
position: "Developer",
salary: 20000
}, {
name: "Vamshi",
position: "Java Developer",
salary: 30000
}, {
name: "Chethan",
position: ".Net Developer",
salary: 10000
}];
model: any = {};
model2: any = {};
addEmployee() {
this.employees.push(this.model);
this.model = {};
}
deleteEmployee(i) {
this.employees.splice(i, 1)
console.log(i);
}
myValue;
editEmployee(k) {
this.model2.name = this.employees[k].name;
this.model2.position = this.employees[k].position;
this.model2.salary = this.employees[k].salary;
this.myValue = k;
}
updateEmployee() {
let k = this.myValue;
for (let i = 0; i < this.employees.length; i++) {
if (i == k) {
this.employees[i] = this.model2;
this.model2 = {};
}
}
}
}
this is the code of app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { ReactiveFormsModule } from '#angular/forms';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
,FormsModule ,ReactiveFormsModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
now i want to add validations to the above code that i dont want to add unfilled fields of data to... i tried many ways couldn't solved the issue..
You should consider setting up forms validation the 'angular way' using reactive forms and angular's form builder.
First you should import the required form classes (assuming you've already configured the appropriate ngModule)
import { FormGroup, FormArray, FormBuilder, Validators } from '#angular/forms';
constructor(
private _fb: FormBuilder
) {.....}
Now you can configure the validation for the form.
this.employeeForm = this.fb.group({
name: ['', Validators.required ],
position: ['', Validators.required ],
salary: ['', Validators.required]
});
How can you prevent the form from submitting unless the data is valid
You can hide/show the submit buttons and remove the click event on the disabled version. See example below...
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default disabled" *ngIf=!employeeForm.valid">update Employee</button>
<button type="submit" class="btn btn-default" *ngIf=employeeForm.valid"(click)="updateEmployee()">update Employee</button>
</div>
For a full working example from angular.io see the link below.
https://angular.io/generated/live-examples/reactive-forms/eplnkr.html

How to add dynamically html controls through the Angular Js in Asp.Net MVC Project?

How to add dynamically html controls through the Angular Js in Asp.NetMVC Project?
just like-i want to add multiple bank details of employee on add button click.
and how can i remove wrong bank details on other remove button click.
To add dynamically bank details page controls through angular js
Step 1: first of all create html page like below code.
Bank.cshtml page
<form class="form-horizontal" enctype="multipart/form-data">
<div ng-repeat="item in ArrBankCtrls">
<div class="form-group">
<label ng-model="item.bankPK_Id" hidden></label>
<label for="BankName" class="col-sm-2 control-label">Bank <i class="mandatStarColor">*</i></label>
<div class="col-sm-6">
<select class="form-control" style="width: 100%;" ng-change="ChangeBankName()" ng-model="item.BankName">
<option selected="selected">--Select Bank--</option>
<option ng-repeat="item in bankName" value="{{item.Value}}">{{item.Text}}</option>
</select>
<span style="color:red;" ng-show="item.requiredBankName">BankName is required !</span>
</div>
<div class="col-sm-2">
<button id="Add" class="btn btn-success" title="Add" ng-click="AddRemoveBank(true,item)">+</button>
<button class="btn btn-danger" ng-model="RemoveBankCtrl" ng-disabled="RemoveBankCtrl" title="Remove" ng-click="AddRemoveBank(false,item)">-</button>
</div>
</div>
<div class="form-group">
<label for="AccountNo" class="col-sm-2 control-label">A/c No. <i class="mandatStarColor">*</i></label>
<div class="col-sm-6">
<input type="text" class="form-control" onlydigits ng-change="ChangeAccountNo($index)" ng-model="item.AccountNo" placeholder="Account No." maxlength="26" required>
<span style="color:red;" ng-show="item.requiredAccountNo">AccountNo is required !</span>
</div>
</div>
<div class="form-group">
<label for="IFSC" class="col-sm-2 control-label">IFSC <i class="mandatStarColor">*</i></label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-change="ChangeIFSC($index)" ng-model="item.IFSC" placeholder="IFSC" maxlength="11" required>
<span style="color:red;" ng-show="item.requiredIFSC">IFSC is required !</span>
<span style="color:red;" ng-show="item.requiredDigitIFSC">Required 11 digit's !</span>
</div>
</div>
<div class="form-group">
<label for="Address" class="col-sm-2 control-label">Address</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="item.Address" placeholder="Address">
</div>
</div>
<div class="form-group">
<label for="CancelCheque" class="col-sm-2 control-label">Cancel Cheque <i class="mandatStarColor">*</i></label>
<div class="col-sm-6">
<input type="file" id="{{ 'CancelCheque-' + this.$index }}" ng-file-select="onFileSelect($files)" onchange="angular.element(this).scope().BankFileChange(this)" ng-model="item.ImgCancelCheque" upload-file="item.CancelCheque" accept=".pdf,.gif,.jpg,.jpeg,.png,.bmp">
<span style="color:red;" ng-show="item.requiredCancelCheque">CancelCheque file is required !</span>
<img src="{{item.ImgCancelCheque}}" alt="Cancel Cheque" class="imgHeightWidth" />
</div>
</div>
</div>
</form>
Angular Js code
//#region To Add/Remove BankDetails controls
$scope.RemoveBankCtrl = true;
$scope.ArrBankCtrls = [{
PK_Id: "",
BankName: "",
AccountNo: "",
IFSC: "",
Address: "",
CancelCheque: ""
}];
$scope.AddRemoveBank = function (flag, item) {
//debugger
var index = this.$index;
if (flag) {
item = { PK_Id: "", BankName: "", AccountNo: "", IFSC: "", Address: "", CancelCheque: "" };
$scope.ArrBankCtrls.push(item);
$scope.RemoveBankCtrl = false;
//#region Set default selected value in ddl
$scope.ArrBankCtrls[($scope.ArrBankCtrls.length - 1)].BankName = "--Select Bank--";
// #endregion
}
else {
//$scope.ArrBankCtrls.pop(item);
$scope.ArrBankCtrls.splice(index, 1);
if ($scope.ArrBankCtrls.length == 1) {
$scope.RemoveBankCtrl = true;
}
}
}
//#region Bind Bank Name ddl
$scope.ArrBankCtrls[0].BankName = "--Select Bank--";
VendorService.postData(strVenUrl + "/GetBank").then(function (data) {
if (data != null) {
$scope.bankName = data;
}
})
// #endregion
// #endregion
Controller.cs Code
#region GetBank
public ActionResult GetBank()
{
dynamic bank = null;
try
{
bank = vendor.Bank();
}
catch (Exception ex)
{
ExceptionError(ex.Message);
}
return Json(bank, JsonRequestBehavior.AllowGet);
}
#endregion
[HttpPost]
public ActionResult InsertBankDetails(List<BankDetails> bankDetails)
{
//Your code
return RedirectToAction("BankDetails");
}
you must have used somewhere collections, bind that collection in the ng-repeat directive, on the button click and add simply remove and add an item from the collection

How to apply jquery plugin: styler in typescript

I want to apply jQueryFormStyler in Angular2/Typescript.
I call in ngAfterViewInit:
jQuery(this.elementRef.nativeElement).find('input').styler();
My typescript component:
import {Component, AfterViewInit, ElementRef} from "#angular/core";
declare var jQuery: any;
#Component({
selector: 'my-app',
template: ` <div class="row">
<div class="col-sm-12 item">
<div class="row">
<div class="col-sm-6 vcenter">
<div class="position">
Java Developer
</div>
<div class="place">
Company name
</div>
</div>
<div class="col-sm-6 vcenter text-right">
<label class="radio-wrapper">
<input type="radio" name="choose-role4">
<span>Viewer</span>
</label>
<label class="radio-wrapper checked">
<input type="radio" name="choose-role4" checked="">
<span>Moderator</span>
</label>
<label class="radio-wrapper">
<input type="radio" name="choose-role4">
<span>HIDE OBJECT</span>
</label>
</div>
</div>
</div>
</div>`
})
export class AppComponent implements AfterViewInit {
elementRef: ElementRef;
constructor(elementRef: ElementRef) {
this.elementRef = elementRef;
}
ngAfterViewInit() {
**jQuery(this.elementRef.nativeElement).find('input').styler();**
}
}
Thank you.

Resources