Dropdown list does not populate with API data in Angular - object

I know that similar questions have been asked, but I've found none with a good answer. I want to create a select list in an Angular form, where the value for each option is an object. I have no backend error and i have no frontend error.
Backend: Spring boot
,Frontend : Angular 9
here is what i've got in option value = [object,object]:
here is what i've got in the browser
here is the Model
export class Societe {
id: number;
nomSociete: String;
registreCommercial: String;
dateConstruction: Date;
formeJuridique: String;
telephone: Number;
fax: Number;
siteWeb: String;
secteur : Secteur;
}
here is the TypeScript component :
export class CreateSocieteComponent implements OnInit {
form: any = {secteur: Secteur};
id: number;
societe: Societe;
secteur: Secteur;
constructor(private tokenStorageService: TokenStorageService,private societeService: SocieteService,
private secteurService: SecteurService , private route: ActivatedRoute, private router: Router) { }
getSelectedSecteur(): void{
this.secteurService.listerSecteur()
.subscribe(secteur => this.secteur= secteur);
}
//methods to get dropdown values
dropDownProjectName: string = '';
selectedHandlerProjectName(event : any)
{
if(event.target.value != 'default') { this.dropDownProjectName = event.target.value;}
else {this.dropDownProjectName = null;}
}
ngOnInit(): void {
this.getSelectedSecteur();
}
here is HTML code :
<div class="dropdown ml-auto">
<select class="btn btn-secondary dropdown-toggle" >
<option value="default">Select Secteur</option>
<option *ngFor="let Secteur of secteur" [value]="secteur">{{secteur}}</option>
</select>
</div>
<button type="submit" class="btn btn-success">Submit</button>
i didn't understand why i'm getting select option [object,object] instead of list of secteur .
ANY HELP !!?

try...
<option *ngFor="let sec of secteur; let i = index" [value]="secteur[i].id">
{{secteur[i].name}}
</option>

Related

Angular form in login.component.html not sending data to login.component.ts

I have a simple login form with email and password and when I try to send data to login.components.ts the form is empty
login.component.html:
<mat-spinner *ngIf="isLoading"></mat-spinner>
<form *ngIf="!isLoading" #loginForm="ngForm" (ngSubmit)="login(loginForm)">
<mat-form-field appearance="fill" class="login-full-width">
<mat-label>Enter your email</mat-label>
<input matInput [formControl]="email" type="email" name="email" placeholder="E-Mail" required>
<mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
</mat-form-field>
<mat-form-field appearance="fill" class="login-full-width">
<mat-label>Enter your password</mat-label>
<input matInput [formControl]="password" name="password" [type]="hide ? 'password' : 'text'" required>
<button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide">
<mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
</button>
</mat-form-field>
<button mat-raised-button color="primary" type="submit">Login</button>
</form>
</mat-card>
login.component.ts
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Component, OnInit } from '#angular/core';
import { FormControl, NgForm, NgModel, Validators } from '#angular/forms';
import { response } from 'express';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit(): void {
}
email = new FormControl('', [Validators.required, Validators.email]);
password = new FormControl('', [Validators.required]);
hide = true;
isLoading = false;
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
login(form: NgForm) {
console.log(form.value); <=========================== this is empty
this.http.post<{message: string}>('http://localhost:3000/login', form.value, this.httpOptions)
.subscribe((responseData) => {
console.log(responseData.message);
})
}
getErrorMessage() {
if (this.email.hasError('required')) {
return 'You must enter a value';
}
return this.email.hasError('email') ? 'Not a valid email' : '';
}
}
Console log is giving empty object
The "hello from express.js" is from the backend, which works fine (even tested with postman)
I think you are making the mistake of combining template-driven forms with reactive forms.
I will suggest using one approach to get the data out of it.
Example [formControl] is a reactive form item and you are submitting the form through the template-driven form. They don't work together.

How to use seach function by "int" in ASP.NET Core MVC?

I use this way add seach function.
But it only can search by string.
I want to add a function of seach by "int".
Anyone have suggest?
public async Task<IActionResult> Index(string searchString)
{
var movies = from m in _context.Movie
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
return View(await movies.ToListAsync());
}
And it is my resource
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-5.0
Also I have try like this way,but it seem didn't work
Search By Number in ASP.NET MVC
To search value by Int parameter, it is similar like search by string. In the View page, set the element's name attribute as same as the parameter name in the action method.
You can check the following sample:
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p>
Find by name: <input type="text" name="searchString" value="#ViewData["CurrentFilter"]" />
Find by ID: <input type="text" name="searchId" value="#ViewData["CurrentID"]" />
<input type="submit" value="Search" class="btn btn-default" /> |
<a asp-action="Index">Back to Full List</a>
</p>
</div>
</form>
Controller:
public async Task<IActionResult> Index(string searchString, int searchId)
{
var students = from stu in _context.Students
select stu;
//if (!String.IsNullOrEmpty(searchString))
//{
// students = students.Where(s => s.LastName.Contains(searchString.ToString()));
//}
if (searchId !=0)
{
students = students.Where(s => s.ID == searchId );
}
ViewData["CurrentFilter"] = searchString;
ViewData["CurrentID"] = searchId;
return View(await students.ToListAsync());
}
Then, the result as below:

How to set a SharePoint list field using a pnp.sp People Picker

I do not know the code to add the user, selected in a People Picker from the pnp.sp library.
I've tried the below code example (by using State) but this I understand is not saving the users selection.
private _getPeoplePickerItems() {
pnp.sp.web.siteUsers.get().then((data) =>{
this.setState({
DeptContact: data
});
});
}
And the people picker in the render:
<PeoplePicker
context={this.props.context}
titleText="People Picker"
personSelectionLimit={3}
groupName={''}
showtooltip={false}
isRequired={false}
disabled={false}
selectedItems={this._getPeoplePickerItems}
showHiddenInUI={false}
principalTypes={[PrincipalType.User]}
resolveDelay={1000}
/>
</div>
</div>
I expect a user to be able to enter a user into the people picker and resolve it and then submit it. This user is then added to a 'Person' column in a sharepoint list.
My test code for your reference(react framework).
import * as React from 'react';
import styles from './PnpReact.module.scss';
import { IPnpReactProps } from './IPnpReactProps';
import { escape } from '#microsoft/sp-lodash-subset';
import pnp from "#pnp/pnpjs";
import { PeoplePicker, PrincipalType } from "#pnp/spfx-controls-react/lib/PeoplePicker";
export interface IDefaultData{
PeoplePickerDefaultItems:string[];
}
export default class PnpReact extends React.Component<IPnpReactProps, IDefaultData> {
public constructor(props: IPnpReactProps,state: IDefaultData){
super(props);
this.state = {
PeoplePickerDefaultItems:[]
};
}
//get users from peoplepicker
private _getPeoplePickerItems(items: any[]) {
console.log(items);
}
public componentDidMount(){
this.GetDefaultUsers();
}
private GetDefaultUsers() {
pnp.sp.web.siteUsers.get().then((items: any[]) =>{
var defaultUsers:string[]=[];
//get last 2 users
for(var i=items.length-1;i>items.length-3;i--){
defaultUsers.push(items[i].Email);
}
this.setState({
PeoplePickerDefaultItems:defaultUsers
});
});
}
public render(): React.ReactElement<IPnpReactProps> {
return (
<div className={ styles.pnpReact }>
<div className={ styles.container }>
<div className={ styles.row }>
<PeoplePicker
context={this.props.context}
titleText="People Picker"
personSelectionLimit={3}
groupName={''}
showtooltip={false}
isRequired={false}
disabled={false}
selectedItems={this._getPeoplePickerItems}
defaultSelectedUsers={this.state.PeoplePickerDefaultItems}
showHiddenInUI={false}
principalTypes={[PrincipalType.User]}
resolveDelay={1000}
/>
<div className={ styles.column }>
<span className={ styles.title }>Welcome to SharePoint!</span>
<p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>
<p className={ styles.description }>{escape(this.props.description)}</p>
<a href="https://aka.ms/spfx" className={ styles.button }>
<span className={ styles.label }>Learn more</span>
</a>
</div>
</div>
</div>
</div>
);
}
}

*ngIf-else not showing else results

I have no idea why this isn't working and I'm stuck. Can anyone spot what is wrong with my code?
Im trying to show a Not found message when there are no tickets to show. I tried getting the result via tickets array lenght, but it always shows that the length is 0.
HTML
<ng-container *ngIf="tickets; else elseTemplate">
<div class="container">
<div class="row justify-content-md-center">
<div class="col-sm-4" *ngFor="let ticket of tickets">
<div class="card">
<h5 class="card-header"><span class="fa fa-ticket"></span> Pileti nr. {{ticket._id}}</h5>
</div>
</div>
</div>
</div>
</ng-container>
<ng-template #elseTemplate>
<div><h1>Ticket not found.</h1></div>
</ng-template>
TS
import { Component, OnInit } from '#angular/core';
import { TicketService } from '../../ticket.service';
import { ActivatedRoute } from '#angular/router';
import * as moment from 'moment';
import {Location} from '#angular/common';
#Component({
selector: 'app-reg-ticket-list',
templateUrl: './reg-ticket-list.component.html',
styleUrls: ['./reg-ticket-list.component.css']
})
export class RegTicketListComponent implements OnInit {
reg: string;
public tickets = [];
constructor(private ticketService: TicketService, private route: ActivatedRoute, private _location: Location) { }
ngOnInit() {
this.reg = this.route.snapshot.params.reg;
this.ticketService.getTicketsByReg(this.reg)
.subscribe(data => this.tickets = data);
}
dateFormat(date) {
moment.locale('et');
return moment(date).format("Do MMMM YYYY HH:mm:ss")
}
goBack() {
this._location.back();
}
}
When using *ngIf="tickets;, this will only check if tickets is falsey, and an empty array is not falsey (although null is).
Instead, you can use *ngIf="tickets && ticket.length; which will also check that there's the length is not 0

Redux Form : How to add function after validation success and before submit

I have a redux form that have a validation. When the validation returns with no errors, it will by default submit to the controller in the handleSubmit().
class SomeComponent extends Component {
constructor(props) {
super(props)
}
render() {
const { handleSubmit, fields: { field }, submitting, values } = this.props;
return (
<form onSubmit={handleSubmit(this.props.someActionForm)}>
<TextField {...field.input}
type="text"
label="FIELD"
floatingLabelText="FIELD"
errorText={field.touched? field.error: null}
/>
<div className="col-xs-12">
<FlatButton
label="ACTIVATE"
fullWidth={true}
style={styles.fullButton}
backgroundColor="#4FCDCC"
hoverColor="#59e5e3"
type="submit"
disabled={submitting}
/>
</div>
</form>
);
}
}
function validate(values) {
const errors = {};
if(!values.field) {
errors.field= "Field must not be empty !!!";
}
return errors;
}
SomeComponent = reduxForm({
form: "SomeComponent",
fields: ['field'],
validate
}, mapStateToProps, mapDispatchToProps )(SomeComponent);
How can I add a function, for example a loading element to be triggered when the validation is successful but before the form submits to the action (handleSubmit())?
Thank you in advance
You can add a class method like this:
class SomeComponent extends Component {
submit(formProps) {
// your logic
this.props.someActionForm(formProps);
};
render() {
const {handleSubmit, fields: {field}, submitting, values} = this.props;
return (
<form onSubmit={handleSubmit(this.submit)}>
<TextField {...field.input}
type="text"
label="FIELD"
floatingLabelText="FIELD"
errorText={field.touched ? field.error : null}
/>
<div className="col-xs-12">
<FlatButton
label="ACTIVATE"
fullWidth={true}
style={styles.fullButton}
backgroundColor="#4FCDCC"
hoverColor="#59e5e3"
type="submit"
disabled={submitting}
/>
</div>
</form>
);
}
}
Notice that you forgot return in render method

Resources