I'm facing an issue with accessing a form from one component to another in my project. One component contains a form, and the other has navigation buttons that, when clicked, should validate the form before moving on to the next step. However, I always encounter the problem of the form being undefined when trying to access it from another component. Is there a way to successfully access the form from another component, and if so, how can I achieve this?
https://i.sstatic.net/UALJs.png
Here's my sample code in plunker
Index.html
<!DOCTYPE html>
<html>
<head>
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ffef1f8eaf3fedaffecfdffa1aaa1b0">[email protected]</a>" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app">
<form-component></form-component>
<nav-component></nav-component>
</body>
</html>
script.js
// Code goes here
function checkForm(form) {
if (form) {
if (form.$valid) {
alert("Form is valid!");
}
else
{
alert("Form is invalid!");
}
}
else {
alert("FAILED! Form is undefined!");
}
}
function formController() {
var model = this;
model.goToNextStep = function(form) {
model.form = form;
checkForm(form);
};
}
function navController() {
var model = this;
model.goToNextStep = function(form) {
model.form = form;
checkForm(form);
};
}
var app = angular.module("app", []);
app.component("formComponent", {
template: `
<div class="container">
<form name="mainForm">
<p>When you click the button that exists in the same component
as the form, everything works fine.\
</p>
<input type="text" name="test123" value="THIS IS A TEST" />
<button type="button" ng-click="model.goToNextStep(mainForm);">
Submit Form
</button>
</form>
<br /><strong>formComponent model:</strong> <pre>{{model | json }}</pre>
</div>
`,
controllerAs: "model",
controller: [formController]
});
app.component("navComponent", {
template: `
<div class="container">
<p>When you click the button that does NOT exist in the same
component as the form, it doesn't work.
</p>
<button type="button" ng-click="model.goToNextStep(mainForm);">Submit Form</button>
<br /><br /><strong>navComponent model:</strong>
<pre>{{model | json }}</pre>
</div>
`,
controllerAs: "model",
controller: [navController]
});